Private Variables with Closures
Hide state behind a function scope.
Privacy Through Closures
JavaScript long lacked a built-in way to make object fields private. Closures provide one: variables inside a function are invisible outside, yet accessible to functions defined within.
function secretBox() {
let secret = "hidden";
return {
reveal: () => secret
};
}
const box = secretBox();
console.log(box.reveal()); // "hidden"
console.log(box.secret); // undefinedA Counter With Private State
The canonical example: a counter whose count cannot be tampered with directly. Only the returned methods can change it.
function makeCounter() {
let count = 0;
return {
increment: () => ++count,
value: () => count
};
}
const c = makeCounter();
c.increment();
c.increment();
console.log(c.value()); // 2All lessons in this course
- How Closures Capture State
- Private Variables with Closures
- The Module Pattern (IIFE)
- Factory Functions