...

/

Discussion: The Permanent Closure

Discussion: The Permanent Closure

Execute the code to understand the output and gain insights into scoping in closure functions.

Verifying the output

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

Press + to interact
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 current value of the variable i ...