JavaScript Scope and Closure Code Traces
Six traces covering the `var` loop-closure pitfall, parameter shadowing, IIFE captures, block scope leaks, and `delete` on locals.
Question Bank
Medium
JavaScript
6 questions
quiz
interview-prep
closures
js-lexical-scope
1,192 views
11
What do these two calls print, and why do they not both log 5?
Examples
Example 1:
Input: arr[2](); arr[3]();
Output: 6; 7
Explanation: All five closures share the same function-scoped i, which is 5 after the loop, so each call increments the same i and logs the new value.const arr = [];
for (var i = 0; i < 5; i++) {
arr[i] = function () {
i++;
console.log(i);
};
}
arr[2]();
arr[3]();What is the output of the following code, and why does outer x stay undefined?
Examples
Example 1:
Input: fn(3); console.log(x); console.log(y);
Output: 12; undefined; 13
Explanation: The parameter x shadows the outer var x so the assignment never reaches it, while y is unshadowed and writes through to the outer binding.var x, y;
var fn = function (x) {
x = 12;
y = 13;
console.log(x);
};
fn(3);
console.log(x);
console.log(y);What does the IIFE print, and which binding does each console.log resolve?
Examples
Example 1:
Input: trace the IIFE
Output: ReferenceError: Cannot access 'name' before initialization
Explanation: The inner let name puts the binding in the temporal dead zone for the entire IIFE block, so the first read throws before the initializer runs.let name = 'foo';
(function () {
console.log('name - before:', name);
let name = 'bar';
console.log('name - after:', name);
})();What is logged here? Why does delete not affect x?
Examples
Example 1:
Input: console.log(example)
Output: 0
Explanation: delete only removes own object properties, never variable bindings or parameters, so x keeps its value of 0.var example = (function (x) {
delete x;
return x;
})(0);
console.log(example);What does each call print, and how does each closure capture x and y?
Examples
Example 1:
Input: generateNum(2)(3).result; generateNum(2)(3).sum(4)
Output: 0; 3
Explanation: result is computed eagerly as 2 - 3 + 1, and sum closes over x = 2 and y = 3 and adds z = 4 to compute 2 - 3 + 4.function generateNum(x) {
return function (y) {
return {
result: x - y + 1,
sum: function (z) {
return x - y + z;
},
};
};
}
console.log(generateNum(2)(3).result);
console.log(generateNum(2)(3).sum(4));What does the following nested closure print?
Examples
Example 1:
Input: outer()
Output: 3
Explanation: var b is hoisted to the top of inner so b++ runs on the local undefined producing NaN, then var b = 3 overwrites it and the log prints 3.var b = 1;
function outer() {
var b = 2;
function inner() {
b++;
var b = 3;
console.log(b);
}
inner();
}
outer();