What are Closures in JavaScript and how do they capture scope variables?
expand_more
function createCounter() {
let count = 0; // captured variable
return {
increment: function() {
count++;
return count;
}
};
}
const counter = createCounter();
console.log(counter.increment()); // 1
console.log(counter.increment()); // 2
In this setup, count is a private variable enclosed within the returned methods, shielded from external manipulation. This is useful for data privacy and encapsulating stateful behavior without global variable pollution.