Junior — Middle
Milline on sulgemiste (closures) roll JavaScriptis ja milleks neid kasutatakse?
sobes.tech AI
Vastus AI-lt
Closures in JavaScript are functions that "remember" the environment in which they were created, including access to variables from an outer function even after it has finished.
Role of closures:
- Allow creating private variables and methods by encapsulating data.
- Used to create functions with preserved state.
- Help avoid pollution of the global scope.
- Used in functional programming to create functions with partially applied arguments.
Example:
function makeCounter() {
let count = 0; // private variable
return function() {
count += 1;
return count;
};
}
const counter = makeCounter();
console.log(counter()); // 1
console.log(counter()); // 2
Here, the inner function retains access to the count variable from the outer function, creating a closure.