0Pricing
JavaScript Academy · Lesson

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);   // undefined

A 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()); // 2

All lessons in this course

  1. How Closures Capture State
  2. Private Variables with Closures
  3. The Module Pattern (IIFE)
  4. Factory Functions
← Back to JavaScript Academy