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?- A. 0,1,2 0,1,2
- B. 3,3,3 0,1,2
- C. 3,3,3 3,3,3
- 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
- Problem: Minimum number of swaps (any two positions) needed to sort an array of distinct values, by counting cycles of the permutation…
- Problem: Count subarrays whose sum lies in [lo, hi] using prefix sums and a sorted list (bisect). python from bisect import bisectleft…
- Problem: Starting at index s, you may jump from i to i + a[i] or i − a[i]. Can you reach any index holding 0? python def canreach(a, s)…
- Problem: Count non-empty subsequences whose minimum + maximum ≤ target (sort, then two pointers with powers of 2). python def count(a, t)…
- Problem: Rotate an array right by k in O(1) extra space with three reversals. python def rotate(a, k): n = len(a); k %= n def rev(i, j)…
- Problem: Count primes in [L, R] with a segmented sieve (mark multiples of small primes up to √R inside the segment). python import math…