Junior — Senior
Creating an array of functions with closure and index output
livecode
Task condition
In the assemblePages function, an array is formed and filled with functions that output the current page number. Each iteration of the loop creates a new function that captures the value of the counter. After the loop finishes, the array is returned, and individual functions can be called to output the desired page numbers.
function assemblePages() {
let pages = [];
let i = 0;
while (i < 10) {
const printPage = function () {
console.log(i);
};
pages.push(printPage);
i++;
}
return pages;
}
let bookReader = assemblePages();
bookReader[0]();
bookReader[5]();
This example demonstrates how a closure retains a reference to the counter variable, so when the functions are called after the loop ends, they output the last value of the counter, not the value at the time of function creation. This is a typical case for discussing closure behavior in JavaScript.