Question Bank
/

JavaScript var Loop Closure: Two Explanations Quiz

JavaScript var Loop Closure: Two Explanations Quiz

The classic var-in-a-for-loop closure trap, explained two ways (shared `i` binding and the IIFE capture fix), plus two companions on the `let` per-iteration binding and a queueMicrotask version of the trap.

Question Bank
Medium
JavaScript
4 questions
quiz
closures
js-lexical-scope
interview-prep

354 views

11

Predict the console output and explain WHY: var declared in the loop header creates a single binding that every closure shares. Walk through what i holds at the moment arr[2]() actually runs.

Examples

Example 1:

Input: see code below
Output: 5
Explanation: All five closures captured the same `i`; the loop has exited and i is 5.
const arr = [];
for (var i = 0; i < 5; i++) {
    arr[i] = function () {
        console.log(i);
    };
}

arr[2]();
// what is logged, and why?