Search⌘ K
AI Features

Discussion: The Permanent Closure

Understand how JavaScript closures work with loop variables by analyzing a common puzzle involving var and unexpected output. Learn to resolve this using let and IIFE techniques, improving your ability to write predictable, encapsulated functions.

Verifying the output

Now, it’s time to execute the code and observe the output.

Javascript (babel-node-es2024)
function createCounterArray() {
const counterArray = [];
for (var i = 0; i < 5; i++) {
counterArray.push(() => {
console.log(`Counter: ${i}`);
});
}
return counterArray;
}
const counters = createCounterArray();
counters.forEach(counter => counter());

Understanding the output

In this puzzle, the intention is to create an array of closure functions, each printing the ...