Junior — Middle
Can you explain what a closure is in JavaScript and how it works?
sobes.tech AI
Answer from AI
A closure in JavaScript is a function that 'remembers' the environment in which it was created, even if that environment is no longer active. In simpler terms, a function inside another function can access the variables of the outer function after the outer function has finished executing.
This works because when a function is created, a reference to the lexical environment where it was declared is stored.
Example:
function outer() {
let count = 0;
return function inner() {
count++;
console.log(count);
};
}
const counter = outer();
counter(); // 1
counter(); // 2
Here, inner closes over the variable count from outer, preserving its state between calls.