Glossary / Private class fields

Private class fields

JavaScript private class fields and methods use names prefixed with # and are enforced by the language. They are not ordinary string-keyed properties, so bracket notation, enumeration, and reflection cannot access them. This differs from TypeScript’s compile-time private modifier and naming conventions such as _value.

Private names and branding

class TokenStore {
  #token;
  constructor(token) { this.#token = token; }
  isCurrent(token) { return this.#token === token; }
}

A private name must be declared in the class body and is lexically visible only to code in that class definition. Access performs a brand check: an object must carry that class’s private brand. A subclass does not gain access to a base class’s private names, although base methods can access the base private state on a valid instance. Private static fields are checked against the class constructor.

Proxies can be surprising: a proxy around an instance generally does not carry the target’s private brand, so calling a method that reads #field with the proxy as this can throw. Private fields are not automatically serialized or cloned as public properties. Use public methods as controlled capabilities and avoid exposing sensitive values unnecessarily; private syntax is encapsulation, not cryptographic secrecy against code that already controls the instance.

When to use

Use #private to enforce class invariants and prevent external mutation. Use public fields for intentionally public state and closures/modules for state not naturally owned by a class. Consider testability and inheritance before making data private; private names cannot be monkey-patched by consumers.

Interview questions

  1. Can obj["#token"] read a private field? No; private names are not string property keys.
  2. Do subclasses access base private fields directly? No, the declaring class’s lexical code owns that private name.
  3. Why can a Proxy cause a private-field error? The proxy may fail the private-brand check even when it wraps a branded target.
  4. Are private fields encryption? No; they enforce language-level encapsulation, not cryptographic secrecy.

References