typestar

Closures as state in JavaScript

A function that outlives its scope keeps the variables it used.

function makeCounter(start = 0) {
  let count = start;
  return {
    increment: () => (count += 1),
    reset: () => (count = start),
    get value() {
      return count;
    },
  };
}

const a = makeCounter();
const b = makeCounter(10);
a.increment();
a.increment();
b.increment();

console.log(a.value, b.value);
a.reset();
console.log(a.value, Object.keys(a));

How it works

  1. Each call to the factory creates fresh state.
  2. Returning several functions shares one private scope.
  3. This is how JavaScript did private fields before #.

Keywords and builtins used here

The run, in numbers

Lines
20
Characters to type
337
Tokens
118
Three-star pace
100 tpm

At the three-star pace of 100 tokens a minute, this run takes about 71 seconds.

Type this snippet

Step 1 of 4 in Closures, step 1 of 16 in Functions & patterns.

Next →