Data Structures & AlgorithmsVery hardGoogle · Flipkart interview

Edge case: closures over a loop variable declared with var versus let in JavaScript.

Edge case: closures over a loop variable declared with var versus let in JavaScript.
const a = [], b = [];
for (var i = 0; i < 3; i++) a.push(() => i);
for (let j = 0; j < 3; j++) b.push(() => j);
console.log(a.map(f => f()).join(","), b.map(f => f()).join(","));
What is printed?
  1. A. 0,1,2 0,1,2
  2. B. 3,3,3 0,1,2
  3. C. 3,3,3 3,3,3
  4. D. 0,1,2 3,3,3

Correct answer: B. 3,3,3 0,1,2

var is function-scoped, so all three closures share one i, which is 3 after the loop. let creates a fresh binding per iteration, so each closure keeps its own j: 0, 1, 2.

More Coding Interview Problems questions

Exams that ask this topic