javascriptadvanced
JavaScript Closures and Scope
Closures, scope chain and hoisting
6 questions
By EZ4Code Team
1. What does the following code output? for (var i = 0; i < 3; i++) { setTimeout(() => console.log(i), 0) }
for (var i = 0; i < 3; i++) {
setTimeout(() => console.log(i), 0)
}3 3 3
0 1 2
0 0 0
Error
Explanation: var is function-scoped; after the loop ends i=3; the setTimeout callbacks share the same i, so they all print 3.
2. If we change var to let in the previous question, what is the output?
0 1 2
3 3 3
0 0 0
Error
Explanation: let is block-scoped; each iteration creates a new i binding, and the setTimeout closures capture their own i, so the output is 0 1 2.
3. What is a closure?
The combination of a function and its lexical environment, enabling inner functions to access outer variables
An anonymous function
An arrow function
An immediately invoked function
Explanation: A closure is the combination of a function and its lexical scope; even after the outer function returns, the inner function can still access outer variables.
4. What does the following code output? function counter() { let n = 0 return () => ++n } const c = counter() console.log(c(), c())
function counter() {
let n = 0
return () => ++n
}
const c = counter()
console.log(c(), c())1 2
0 1
1 1
Error
Explanation: The returned arrow function forms a closure, holding a reference to n; each call increments, so the output is 1 2.
5. Which description of variable hoisting is correct?
var declarations are hoisted and initialized to undefined; let/const are hoisted but have a temporal dead zone
let/const are not hoisted
Only function declarations are hoisted
var declarations are not hoisted
Explanation: var, let, const, and function declarations are all hoisted; var is initialized to undefined, while accessing let/const in the temporal dead zone (TDZ) throws an error.
6. What is one of the main uses of an IIFE (Immediately Invoked Function Expression)?
Creating an independent scope to avoid polluting the global scope
Speeding up code
Replacing Promise
Declaring constants
Explanation: An IIFE creates an independent function scope; before ES6 modules/block scope became common, it was often used to encapsulate private variables and avoid global pollution.
More javascript Quizzes
JavaScript Basics Quiz
beginnerVariables, types, operators, functions, and core JavaScript concepts.
JavaScript ES6+ Quiz
intermediateArrow functions, destructuring, promises, modules, and modern JavaScript features.
JavaScript DOM Manipulation
intermediateDOM manipulation and event handling
JavaScript Asynchronous Programming
intermediatePromise, async/await, fetch
JavaScript Array Methods
intermediatemap, filter, reduce and other array higher-order methods