Middle
Can you explain what a closure is?
sobes.tech AI
Answer from AI
A closure is a function along with its lexical environment, in which it was created. This means that the function "remembers" variables from the outer scope, even if that outer function has already finished executing.
Example:
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 closes over the variable count from the outer function makeCounter, preserving its state between calls.