Skip to content

Classes & Private State

The Course
•
20 min study

A class combines construction with methods. new Counter(2) creates an instance, runs its constructor, and gives it access to methods on Counter.prototype. Each instance has its own fields; methods declared normally are shared through the prototype.

A field beginning with # is JavaScript private state, not a naming convention. Only the declaring class body can access it. A method using a private field also requires an instance carrying that private field; borrowing it onto an unrelated object fails. Public properties and private fields are different mechanisms.

Use a class when instances with behavior and a lifecycle make your API clearer. A closure is still a valid alternative. Prefer composition—holding another collaborator—over inheritance when you only need to reuse a capability. This library's custom error will extend Error because it truly is an error; other helpers need no inheritance hierarchy.

Avoid arrow instance fields just to make every method automatically bound: that allocates a separate function per instance. Choose an explicit callback closure where needed.

From a factory to a class

Intermediate code built objects with factory functions and closures. A class is another way to write the same idea, with three parts you will meet in every class: a constructor that sets up each instance, methods shared through the prototype, and new to create an instance.

A factory and a class side by side JavaScript
function makeCounter(start) {
  let value = start;
  return {
    increment() {
      value += 1;
      return value;
    }
  };
}

class Counter {
  constructor(start) {
    this.value = start;
  }

  increment() {
    this.value += 1;
    return this.value;
  }
}

const a = makeCounter(0);
const b = makeCounter(10);
const c = new Counter(0);
const d = new Counter(10);

console.log(a.increment(), b.increment(), c.increment(), d.increment());
console.log(a.increment === b.increment, c.increment === d.increment);
console.log(Object.getPrototypeOf(c) === Counter.prototype, Object.keys(c).join(","));
Check your prediction
Text
1 11 1 11
false true
true value

Both shapes give each counter its own state. The factory builds a new increment function for every object, so a.increment === b.increment is false; the class defines increment once on Counter.prototype, and every instance finds it by the prototype lookup from the previous lesson. new Counter(0) creates an empty object whose prototype is Counter.prototype, runs constructor with this bound to it, and returns it. The class's value is an ordinary public property, which Object.keys lists: the next section replaces it with a private field.

Predict, run, and explain

Write the output and trace the important state changes before checking it. Then run the program. Each editor is independent. Async examples end with main() so this editor waits for their work.

Predict, then run JavaScript
class Counter {
  #value;

  constructor(start = 0) {
    this.#value = start;
  }

  add(amount) {
    this.#value += amount;
    return this.#value;
  }
}

const first = new Counter();
const second = new Counter(10);

console.log(first.add(2));
console.log(second.add(1));
console.log(first.add === second.add);
Check your prediction
Text
2
11
true

Read a getter like a property

A getter runs a function when a property is read. Inside a class, get current() { return this.#value; } exposes the value as counter.current, without parentheses. It does not create a separate stored copy. With no setter, callers cannot assign through that property, but methods can still change the private field. Use this syntax in the exercise below.

Choose where state and behavior live

An instance owns its fields; ordinary class methods are looked up on the prototype. Sharing the method does not mean sharing its state. The receiver identifies which instance’s fields the method uses on each call.

Private fields restrict access to code in the declaring class. They do not automatically make instances immutable or bind their methods. Compare a private-field class with the closure factories from intermediate: both can own state, and the useful choice depends on the public API you need.

Choose where state and behavior live: trace JavaScript
class Counter {
  #count = 0;

  next() {
    return ++this.#count;
  }

  get current() {
    return this.#count;
  }
}

const a = new Counter();
const b = new Counter();

a.next();
a.next();
console.log(a.current, b.current);
console.log(a.next === b.next);
Check your prediction
Text
2 0
true

The method function is shared, while the two private counts are independent. The getter is accessed as a property; invoking a.current() would try to call a number.

Choose where state and behavior live: contrast JavaScript
class Counter {
  #count = 0;

  next() {
    return ++this.#count;
  }
}

const counter = new Counter();
// Reading the method does not keep counter as its receiver.
const detached = counter.next;

try {
  // This call has no receiver, so accessing #count throws.
  detached();
} catch (error) {
  console.log(error instanceof TypeError);
}

// Calling through counter supplies the receiver and updates its count.
console.log(counter.next());
Check your prediction
Text
true
1

A private field cannot be read from a missing or unrelated receiver. The failed detached call does not increment the valid instance; a later proper method call still starts at one.

Try the rule on new inputs

Write the same small counter as a closure factory and as a class. Compare receiver requirements, instance state and public methods. Do not introduce inheritance merely because you chose class syntax.

Trace the contract before building

A private field belongs to instances created with that field's declaring class. Borrowing a method does not install its private state on another object. Separate this receiver requirement from a public property merely named similarly.

Trace two instances through interleaved operations. Their state should remain independent while their ordinary methods are found through the prototype. A class encapsulates representation, but only constructor and update rules establish valid state. A negative limit is not rejected automatically because the field starts with #. Keep construction, failed updates and repeated calls in the contract table.

Your turn

Exercise

A queue that keeps its array private

Write a TaskQueue class that stores task names in a private array. add(name) trims the name, appends it and returns the new length; a blank or non-string name throws a TypeError and adds nothing. An items getter lets callers read the tasks, but code that edits what the getter returned must not change the queue. A static isQueue(value) reports whether a value is a real TaskQueue by checking for the private field. Two queues must be independent. Print:

Text
1 2 0
fetch,parse 0
true false
TypeError 2
Your workspace JavaScript
class TaskQueue {
  // Add #items, add(name), get items and static isQueue.
}

const queue = new TaskQueue();
console.log(queue.add?.("fetch"), queue.items);
Hint 1: the idea

A private field stops outside code from naming your state, but if a method hands out the array itself, the caller holds a reference to the same array and can push into it. Keeping an invariant means never giving out a reference you are not willing to have changed. #field in value is the language's own "was this built by my class?" test.

Hint 2: a first step

Declare #items = []; in the class body so every instance gets its own array, and write add without validation first. Then write the getter as return this.#items; and run the test: queue.items.join(",") will show sneaked in. That leak is what the getter has to prevent.

Show one solution
JavaScript
class TaskQueue {
  #items = [];

  add(name) {
    if (typeof name !== "string" || name.trim() === "") {
      throw new TypeError("task name must be non-blank text");
    }
    this.#items.push(name.trim());
    return this.#items.length;
  }

  get items() {
    return [...this.#items]; // a copy: callers cannot edit the queue through it
  }

  static isQueue(value) {
    return #items in value;
  }
}

const queue = new TaskQueue();
const other = new TaskQueue();

console.log(queue.add(" fetch "), queue.add("parse"), other.items.length);

const view = queue.items;
view.push("sneaked in");
console.log(queue.items.join(","), Object.keys(queue).length);
console.log(TaskQueue.isQueue(queue), TaskQueue.isQueue({ items: [] }));

try {
  queue.add("  ");
} catch (error) {
  console.log(error.name, queue.items.length);
}
Text
1 2 0
fetch,parse 0
true false
TypeError 2

#items = [] is a field initializer, evaluated once per new, so other starts with its own empty array rather than sharing one. The getter returns [...this.#items], so the view.push changed only the copy and the queue still reads fetch,parse; returning this.#items directly would print fetch,parse,sneaked in. Object.keys is 0 because private fields are not properties. The validation runs before push, so the rejected blank name leaves the length at 2. isQueue uses #items in value: a plain object with a public items array cannot pass it.

Change it and test it

Try reading #value outside the class: this is a syntax error, so restore the code afterward. Then pass () => first.increment() as a callback. Explain why private state does not make an object immutable or make a callback automatically bound.

Was this article helpful?

Your response is saved on this device.