Question Bank
JavaScript Scope and Closure Code Traces
Difficulty: Medium
Six traces covering the `var` loop-closure pitfall, parameter shadowing, IIFE captures, block scope leaks, and `delete` on locals.
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.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.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.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.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.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.