← All material

Core JavaScript · 2 of 9

Closures Instead of Classes

State does't have to mean "put it in a class" in TS code:

The old way

class Counter {
  private count = 0;

  public increment(): void {
    this.count += 1;
  }

  public getValue(): number {
    return this.count;
  }
}

Using a closure

You can have state without classes by using closures:

const createCounter = () => {
  let count = 0;

  const increment = () => {
      count += 1;
    };

  const getCount = () => {
      return count;
    };

  return { increment, getCount };
};

const counter = createCounter();
button.addEventListener("click", counter.increment); // just works

count is private by scope — nothing outside the closure can reach it. And because increment doesn't read this at all, it behaves the same no matter how it's called or passed around.

Now its a small function that won't get extended or instantiated multiple times like a class would.