Middle
What is a closure? Can you explain?
sobes.tech AI
Answer from AI
Closure is a function together with the lexical environment in which it was created. This means that the function 'remembers' variables from the outer scope, even if the outer function has already finished execution.
Example in JavaScript:
function makeCounter() {
let count = 0;
return function() {
count++;
return count;
};
}
const counter = makeCounter();
console.log(counter()); // 1
console.log(counter()); // 2
Here, the inner function retains access to the variable count from the outer function makeCounter, creating a closure. This allows maintaining state between function calls.