in its lexical scope. Consider the following scenario: A function outer defines a variable x and returns an inner function that references x. The inner function is invoked after outer has finished executing. What happens to x in the closure’s scope chain if outer is called multiple times, creating multiple closures?
Each invocation of outer creates a new scope with its own x, and the inner function (closure) retains access to its specific scope’s x. This ensures independence between closures.
function createFunctions() {
let funcs = [];
for (var i = 0; i < 3; i++) {
funcs.push(function() {
return i;
});
}
return funcs;
}
let result = createFunctions();
console.log(result[0](), result[1](), result[2]());
The var keyword creates a single i in the function scope, shared by all closures. When the closures are invoked, i has already reached 3 after the loop, so all functions return 3.
diagram at the point where inner is invoked:
function outer() {
let x = 10;
function inner() {
console.log(x);
}
x = 20;
return inner;
}
let fn = outer();
fn();
In the memory diagram, the closure’s scope chain includes outer’s scope with x. What value of x is logged when fn() is called, and why?
Closures capture variables by reference, not value. When fn() is called, inner accesses x from outer’s scope, which was updated to 20 before outer returned.
Immediately Invoked Function Expression (IIFE) to create a closure:
let obj = {};
for (let i = 0; i < 2; i++) {
obj[`key${i}`] = (function(x) {
return function() {
return x;
};
})(i);
}
console.log(obj.key0(), obj.key1());
What is the output of the above code?
The IIFE creates a new scope for each iteration, capturing the current value of i as x. Each closure returned by the IIFE retains its own x, resulting in obj.key0() returning 0 and obj.key1() returning 1.