← Back to JavaScript, page 9

javascript-0171 · Medium mid

How do private class fields, private methods, and static initialization blocks work, and how are they different from the underscore convention?

A name starting with # declares a private field or method that only code written inside the class body can access. The rule is enforced by the language, so outside code, subclasses, Object.keys, and JSON.stringify cannot see it, and reading a missing one throws a TypeError. The syntax `#x in obj` checks whether an object has the private field. Static blocks run once when the class is defined, in order with static fields, so they can do multi-step setup.

Full answer

Private members use a # prefix: #count = 0;, #log() {}, static #instances = 0;. They are not properties. They live in a separate slot on the object, so obj['#count'], Object.keys(obj), JSON.stringify(obj), Reflect.ownKeys(obj), and for...in do not show them. Using obj.#count outside the class body is a SyntaxError at parse time, which is a stronger guarantee than the old _count naming convention, where anyone could still read and write the property.

Behaviors to know:

  • Each class that declares a private name has its own slot. A subclass cannot access a private field of its parent, even though the instance has it. The parent has to expose a method or accessor.
  • Reading a private field from an object that does not have it throws a TypeError. There is no undefined result. This is also true for a Proxy wrapping an instance: the proxy does not have the slot, so calling a method that uses private fields through a proxy can fail unless the method is bound to the target.
  • Brand checks: #field in obj returns true when obj was created by this class. It replaces instanceof-style duck typing for internal checks, and it works for objects from other realms.
  • Private methods and accessors (#compute(), get #value()) are installed once per class, not per instance, so they are cheaper than arrow-function fields.
  • Private fields are initialized in order of declaration, before the constructor body in a base class and right after super() returns in a derived class.
  • Private names are not available through reflection. Tests should check behavior through the public API instead.
  • static #x is private to the class itself, and this.#x in a static method called on a subclass fails, since this is the subclass. Use the class name: Counter.#x.

Static blocks, static { ... }, run once during class definition together with static fields, in source order. They are useful for multi-statement setup that does not fit one expression, for example building a lookup table, or filling a static registry that needs access to private static fields.

Trade-offs: private fields cannot be monkey-patched in tests, they are not copied by spread or structuredClone, and older runtimes need a transpiler. Use them for invariants that must not be broken, and keep plain properties for data that other code may read.

javascript
class Counter {
  static #created = 0;
  static registry = [];
  static {
    Counter.registry.push('static block ran, created = ' + Counter.#created);
  }

  #count = 0;
  label;

  constructor(label) {
    this.label = label;
    Counter.#created++;
  }

  #log(message) {
    return `[${this.label}] ${message}`;
  }

  increment() {
    this.#count++;
    return this.#log('count is ' + this.#count);
  }

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

  static isCounter(candidate) {
    return #count in candidate;
  }

  static get created() {
    return Counter.#created;
  }
}

class LoudCounter extends Counter {
  shout() {
    return this.increment().toUpperCase();
  }
  peek() {
    try {
      return this['#count'];
    } catch (error) {
      return error.name;
    }
  }
}

const a = new Counter('a');
a.increment();
console.log(a.increment(), a.value);
console.log('keys:', Object.keys(a), 'ownKeys:', Reflect.ownKeys(a), 'json:', JSON.stringify(a));
console.log('property named #count:', a['#count']);
console.log('isCounter:', Counter.isCounter(a), Counter.isCounter({}), Counter.isCounter(new LoudCounter('b')));
console.log('registry:', Counter.registry);

const loud = new LoudCounter('loud');
console.log(loud.shout(), loud.peek(), Counter.created);

try {
  Counter.prototype.increment.call({});
} catch (error) {
  console.log('wrong object:', error.name);
}

const proxy = new Proxy(a, {});
try {
  proxy.increment();
} catch (error) {
  console.log('through a proxy:', error.name);
}
console.log('proxy with bound method:', Counter.prototype.increment.call(a));

try {
  new Function('class T { #secret = 1; } new T().#secret;');
} catch (error) {
  console.log('outside access at parse time:', error.name);
}
console.log('copy with spread:', { ...a });

Run with Node.js v24.22.1 as js-171.js; two runs gave identical output. Output: [a] count is 2 2 keys: [ 'label' ] ownKeys: [ 'label' ] json: {"label":"a"} property named #count: undefined isCounter: true false true registry: [ 'static block ran, created = 0' ] [LOUD] COUNT IS 1 undefined 3 wrong object: TypeError through a proxy: TypeError proxy with bound method: [a] count is 3 outside access at parse time: SyntaxError copy with spread: { label: 'a' }

Key points

  • #name members are language-enforced: invisible to keys, JSON, and reflection, and a SyntaxError outside the class.
  • Subclasses cannot access a parent's private fields; wrong-object access throws a TypeError.
  • #field in obj is a reliable brand check.
  • Private methods are shared per class; arrow fields are per instance.
  • Static blocks run once, in order with static fields, for multi-step setup.

Common mistakes

  • Expecting a subclass to read a parent's private field.
  • Wrapping instances in a Proxy and then calling methods that use private fields.
  • Relying on private fields for security, when they only protect against accidental access in the same program.
  • Testing private members directly instead of through public behavior.

Follow-ups

  • How does a private field differ from a closure variable in a factory function?
  • What does #x in obj give you that instanceof does not?
  • When would you prefer a WeakMap for private data?

Tips

  • Say the guarantee: language-enforced, not a naming convention.
  • Mention brand checks and the Proxy trap.
  • Explain that static blocks give multi-statement setup in class scope.