In this blog post, we've curated a set of 20+ multiple-choice questions to challenge your understanding of essential JavaScript basic and advanced concepts. Each question comes with detailed explanations to help you learn and reinforce your knowledge. Let's dive in and see how well you know JavaScript!
1. What will be the output of the following code snippet?
var x = 5;
console.log(x + "5");
a) 55
b) 10
c) "55"
d) "5 + 5"
Answer:
c) "55"
Explanation:
In JavaScript, the + operator is used for both addition and string concatenation. Since one of the operands is a string, JavaScript performs string concatenation, resulting in "55".
2. What is the correct way to check if a variable x is of type "string" in JavaScript?
a) if (x === "string")
b) if (typeOf x === "string")
c) if (typeof x === "string")
d) if (x.type === "string")
Answer:
c) if (typeof x === "string")
Explanation:
The typeof operator is used to check the type of a variable in JavaScript. To check if x is of type "string", you would use typeof x === "string".
3. What will be the output of the following code snippet?
var num = 10;
function increment() {
num++;
}
increment();
console.log(num);
a) 9
b) 10
c) 11
d) NaN
Answer:
c) 11
Explanation:
The function increment increments the value of the variable num by 1. When calling increment() and then logging the value of num, it will be 11.
4. What is the output of the following code snippet?
console.log(2 + 3 + "5");
a) 55
b) 10
c) 235
d) "55"
Answer:
d) "55"
Explanation:
In JavaScript, the + operator is used for both addition and string concatenation. Since the first two operands are numbers, they are added together, resulting in 5. Then, the string "5" is concatenated, giving us "55".
5. What is the output of the following code snippet?
var x = 10;
function foo() {
var x = 5;
console.log(x);
}
foo();
console.log(x);
a) 10, 10
b) 10, 5
c) 5, 10
d) 5, 5
Answer:
b) 5, 10
Explanation:
Within the function foo, a new variable x is declared with a value of 5. When calling foo(), it logs the local variable x with a value of 5. However, the global variable x with a value of 10 remains unchanged outside the function.
6. What will be the output of the following code snippet?
var name = "John";
function sayName() {
console.log(name);
var name = "Jane";
}
sayName();
a) John
b) Jane
c) Undefined
d) ReferenceError
Answer:
c) Undefined
Explanation:
In JavaScript, variables declared with var are hoisted to the top of their scope. Inside the sayName function, a local variable name is declared with the value "Jane". Before the variable assignment, the console.log(name) statement is executed, and at that point, the local variable name is hoisted but not yet assigned a value, resulting in an undefined.
7. What will be the output of the following code snippet?
var fruits = ["apple", "banana", "orange"];
console.log(fruits[1]);
a) "apple"
b) "banana"
c) "orange"
d) undefined
Answer:
b) "banana"
Explanation:
In JavaScript arrays, elements are indexed starting from 0. So, fruits[1] will access the second element of the array, which is "banana".
8. What will be the output of the following code snippet?
var arr = [1, 2, 3, 4, 5];
var slicedArr = arr.slice(1, 4);
console.log(slicedArr);
a) [1, 2, 3]
b) [2, 3, 4]
c) [2, 3, 4, 5]
d) [1, 2, 3, 4]
Answer:
b) [2, 3, 4]
Explanation:
The slice() method in JavaScript returns a new array containing elements from the original array specified by the starting and ending indexes (excluding the element at the ending index). In this case, it extracts elements at positions 1, 2, and 3, which are [2, 3, 4].
9. How do you convert a string "123" to a number in JavaScript?
a) parseInt("123")
b) convertNumber("123")
c) toNumber("123")
d) number("123")
Answer:
a) parseInt("123")
Explanation:
The parseInt() function in JavaScript is used to parse a string and convert it into an integer.
10. What will be the output of the following code snippet?
var numbers = [1, 2, 3, 4, 5];
var sum = 0;
numbers.forEach(function (num) {
sum += num;
});
console.log(sum);
a) 1
b) 15
c) 10
d) [1, 2, 3, 4, 5]
Answer:
b) 15
Explanation:
The forEach() method iterates through each element of the numbers array and adds its value to the variable sum. After the loop, the sum will contain the sum of all the numbers in the array, which is 15.
11. What will be the output of the following code snippet?
var numbers = [1, 2, 3, 4, 5];
var squaredNumbers = numbers.map(function (num) {
return num * num;
});
console.log(squaredNumbers);
a) [1, 2, 3, 4, 5]
b) [2, 4, 6, 8, 10]
c) [1, 4, 9, 16, 25]
d) [1, 8, 27, 64, 125]
Answer:
c) [1, 4, 9, 16, 25]
Explanation:
The map() method creates a new array squaredNumbers by squaring each element of the numbers array.
12. What will be the output of the following code snippet?
var numbers = [1, 2, 3, 4, 5];
var evenNumbers = numbers.filter(function (num) {
return num % 2 === 0;
});
console.log(evenNumbers);
a) [1, 3, 5]
b) [2, 4]
c) [1, 2, 3, 4, 5]
d) [true, false, true, false, true]
Answer:
b) [2, 4]
Explanation:
The filter() method creates a new array evenNumbers containing only the elements from the numbers array that is even (i.e., divisible by 2).
13. What will be the output of the following code snippet?
function outer() {
var x = 10;
function inner() {
console.log(x);
}
return inner;
}
var closureFunction = outer();
closureFunction();
a) 10
b) 20
c) undefined
d) ReferenceError
Answer:
a) 10
Explanation:
This code demonstrates a concept known as "closures" in JavaScript. When the outer function is called, it defines a variable x with a value of 10 and then returns the inner function. The inner function, even after being returned from the outer, still retains access to its parent scope, including the variable x. When closureFunction is invoked, it logs the value of x, which is 10.
14. What will be the output of the following code snippet?
var x = 5;
function outer() {
function inner() {
console.log(x);
}
var x = 10;
return inner;
}
var closureFunction = outer();
closureFunction();
a) 5
b) 10
c) 20
d) ReferenceError
Answer:
b) 10
Explanation:
In this code, the x variable is declared in the global scope with a value of 20. When outer is called, it changes the value of the global x to 10. Then, the inner function logs the value of the modified global x, which is 10.
15. What will be the output of the following code snippet?
function delayLog() {
for (var i = 1; i <= 5; i++) {
setTimeout(function () {
console.log(i);
}, 1000);
}
}
delayLog();
a) 1, 2, 3, 4, 5
b) 5, 5, 5, 5, 5
c) 6, 6, 6, 6, 6
d) 1, 6, 6, 6, 6
Answer:
c) 6, 6, 6, 6, 6
Explanation:
This code illustrates a common mistake related to closures and setTimeout. When delayLog is called, it sets up five setTimeout calls, each logging the variable i. The issue is that by the time the setTimeout callbacks execute, the loop has already finished, and the value of i is 6. Since JavaScript uses function-level scope, each callback references the same i variable from the delayLog function, which now holds the value 6. Hence, the output is five consecutive logs of 6.
16. What will be the output of the following code snippet?
function foo() {
return new Promise(function (resolve, reject) {
setTimeout(function () {
resolve("Promise resolved.");
}, 1000);
});
}
console.log("Start");
foo().then(function (result) {
console.log(result);
});
console.log("End");
a) Start, Promise resolved., End
b) Start, End, Promise resolved.
c) Promise resolved., Start, End
d) Start, End, Promise resolved.
Answer:
b) Start, End, Promise resolved.
Explanation:
This code uses a JavaScript Promise to handle asynchronous operations. When executed, it logs "Start", calls the foo function, which returns a Promise that resolves after 1000ms, and then logs "End". After the Promise resolves, the then method is called, which logs the resolved value "Promise resolved." As, with the previous example, asynchronous operations do not block the main thread, so "End" is logged before the Promise resolution.
17. What will be the output of the following code snippet?
async function foo() {
return "Async function.";
}
console.log("Start");
foo().then(function (result) {
console.log(result);
});
console.log("End");
a) Start, Async function., End
b) Start, End, Async function.
c) Async function., Start, End
d) Start, End, Async function.
Answer:
b) Start, End, Async function.
Explanation:
The foo function is marked as async, which means it returns a Promise implicitly. When executed, it logs "Start", calls the foo function, which returns the resolved value "Async function.", and logs "End". After the Promise resolves, the then method is called, which logs the resolved value "Async function." As with previous examples, asynchronous operations do not block the main thread, so "End" is logged before the Promise resolution.
18. What will be the output of the following code snippet?
function* fibonacciGenerator() {
let a = 0;
let b = 1;
while (true) {
yield a;
[a, b] = [b, a + b];
}
}
const fibonacci = fibonacciGenerator();
console.log(fibonacci.next().value);
console.log(fibonacci.next().value);
console.log(fibonacci.next().value);
console.log(fibonacci.next().value);
console.log(fibonacci.next().value);
a) 0, 1, 1, 2, 3
b) 0, 1, 2, 3, 4
c) 1, 1, 2, 3, 5
d) 0, 1, 1, 3, 5
Answer:
a) 0, 1, 1, 2, 3
Explanation:
The fibonacciGenerator function is a generator function that yields the Fibonacci sequence indefinitely. It starts with variables a and b initialized to 0 and 1, respectively. Then, it enters a while (true) loop, which means it will generate Fibonacci numbers infinitely. In each iteration, it yields the current value of a, and then it calculates the next Fibonacci number by updating a and b. When calling fibonacci.next().value, it keeps generating the next Fibonacci numbers in sequence, which are 0, 1, 1, 2, 3, and so on.
19. What will be the output of the following code snippet?
Promise.resolve("First resolved.")
.then(function (result) {
console.log(result);
return Promise.resolve("Second resolved.");
})
.then(function (result) {
console.log(result);
return Promise.resolve("Third resolved.");
})
.then(function (result) {
console.log(result);
return Promise.reject(new Error("Fourth rejected."));
})
.catch(function (error) {
console.log(error.message);
});
a) First resolved., Second resolved., Third resolved., Fourth rejected.
b) First resolved., Second resolved., Third resolved., Error: Fourth rejected.
c) First resolved., Second resolved., Third resolved., Promise {<rejected>: Error: Fourth rejected.}
d) First resolved., Second resolved., Third resolved., Promise {<rejected>: "Fourth rejected."}
Answer:
b) First resolved., Second resolved., Third resolved., Error: Fourth rejected.
Explanation:
This code demonstrates chaining multiple then handlers and a catch handler on Promises. Each then-handler processes the result of the previous then-handler and returns a new Promise. The console.log statements inside each then handler log the values "First resolved.", "Second resolved.", and "Third resolved." The final then handler in the chain returns a rejected Promise with the error "Fourth rejected." The catch handler catches the error and logs its message "Error: Fourth rejected."
20. What will be the output of the following code snippet?
async function asyncFunction() {
throw new Error("Error in async function.");
}
console.log("Start");
asyncFunction().catch(function (error) {
console.log(error.message);
});
console.log("End");
a) Start, Error in async function., End
b) Start, End, Error in async function.
c) Error in async function., Start, End
d) Start, End, Error in async function.
Answer:
b) Start, End, Error in async function.
Explanation:
The asyncFunction is an async function that throws an Error object with the message "Error in async function." The surrounding code uses the catch handler to handle the thrown Error. When executed, it logs "Start", starts the execution of the asyncFunction, which immediately throws the Error, catches the error in the catch block, logs the error message "Error in async function.", and finally logs "End". Asynchronous operations do not block the main thread, so "End" is logged after handling the thrown Error.
Conclusion
Congratulations on completing the JavaScript coding quiz! We hope you enjoyed the challenge and gained a deeper understanding of essential JavaScript basic and advanced concepts. JavaScript is a versatile language, and continuous learning and practice are key to becoming proficient in it.
Keep exploring and building exciting projects to enhance your JavaScript skills. Happy coding!
Comments
Post a Comment
Leave Comment