Middle
How does closure work in JavaScript? Explain using the example of the variable index and the function run in your solution.
sobes.tech AI
Answer from AI
In JavaScript, a closure is a function that remembers its lexical environment even when it is called outside its scope.
Let's consider an example with a variable index and a function run:
function createRunner() {
let index = 0;
function run() {
console.log(index);
index++;
}
return run;
}
const runner = createRunner();
runner(); // 0
runner(); // 1
runner(); // 2
Here, the run function closes over the variable index from the outer createRunner function. Even after createRunner has finished executing, run still has access to index and can modify its value. This allows maintaining state between calls to the run function.
Thus, closures enable creating functions with private variables and maintaining state without using global variables.