Browse topics

Private class fields

Version
es2025
Since
es2022
Review
Draft

Summary#

A class member whose name starts with # is accessible only inside the class body that declares it. The in operator can test whether an object has that private member.

Syntax#

js
class Example {
  #value = 0;
  static has(object) {
    return #value in object;
  }
}

Example#

js
class Counter {
  #count = 0;

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

  static isCounter(/** @type {object} */ value) {
    return #count in value;
  }
}

const counter = new Counter();
console.log(counter.increment(), counter.increment());
console.log(Object.keys(counter).length, JSON.stringify(counter));
console.log(Counter.isCounter(counter), Counter.isCounter({}));

Expected output#

Text
1 2
0 {}
true false

Common mistakes#

Subclasses cannot read a parent class's # fields directly. In a static method, access a private static member through its declaring class. this.#member throws a TypeError when the method is called on a subclass. The right side of #field in value must be an object.

Version applicability#

ES2022 added private fields, private methods and the #field in object check. Earlier runtimes need transpilation or another pattern such as a WeakMap.

Sources#

Attribution
DevLookup contributors
License
CC-BY-4.0