JavaScript classes and private fields

class provides syntax for constructing objects with shared methods. A # field is private class state and can only be accessed from the declaring class's body.

JavaScript
class Counter {
  #value = 0;
  increment() { this.#value += 1; }
  get value() { return this.#value; }
}
const first = new Counter();
const second = new Counter();
first.increment();
first.increment();
console.log(first.value, second.value);
if (second.value !== 0) throw new Error("shared state");
Read the full lesson