Junior — Middle
Kas sa saad selgitada, mis on sulgemine JavaScriptis ja kuidas see töötab?
sobes.tech AI
Vastus AI-lt
Closure in JavaScript is a function that «remembers» the environment in which it was created, even if that environment is no longer active. Simply put, 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 preserved.
Example:
function outer() {
let counter = 0;
return function inner() {
counter++;
console.log(counter);
};
}
const counter = outer();
counter(); // 1
counter(); // 2
Here, inner closes over the variable counter from outer, maintaining its state between calls.