Skip to content
jshacks.dev
Fundamentals

Private Class Fields and Methods in JavaScript With a Hash

A hash-prefixed class member is visible only inside the class body and enforced by the engine. See private fields, methods, brand checks and the proxy catch.

8 min read
Summarize in AI
Flat illustration of an editor window full of code, with the JavaScript, TypeScript, Vite and Node.js logos.

For twenty years, JavaScript's answer to how to make a field private was a convention: a leading _ on the name that meant "please do not touch", enforced by nothing. ES2022 added real privacy. A name that starts with # inside a class body is visible to that body and nobody else, and the engine, not a style guide, enforces it. The feature is small and has consequences that surprise people coming from other languages: private members are not properties, they are not inherited, and they interact oddly with proxies and serialization. This post shows each rule with output from Node.js 24, covers private methods, static privates and the brand check, and compares private fields with the older patterns. The class machinery itself is covered in the post on classes being functions.

The basic rules

A private field is declared with # in the class body and read with the same prefix.

JavaScript
class Account {
  #balance = 0;
  owner;

  constructor(owner, opening) {
    this.owner = owner;
    this.#balance = opening;
  }

  deposit(amount) {
    if (amount <= 0) throw new RangeError("amount must be positive");
    this.#balance += amount;
    return this;
  }

  get balance() {
    return this.#balance;
  }
}

const account = new Account("Ada", 100).deposit(50);

console.log(account.balance);
console.log(account.owner);
console.log(account.balance === account["#balance"]);
console.log(Object.keys(account));
console.log(JSON.stringify(account));
console.log({ ...account });
console.log(account);
Text
150
Ada
false
[ 'owner' ]
{"owner":"Ada"}
{ owner: 'Ada' }
Account { owner: 'Ada' }

The balance is reachable only through the getter. The string key "#balance" is not the private field, so account["#balance"] is undefined, which is a plain property lookup that finds nothing. The private field is absent from Object.keys(), from JSON, from spread, and even from the printed object, because it is not a property at all. That absence is the key difference from the _ naming convention, where _balance was an ordinary property that serialized and could be read.

Outside access is a syntax error

Writing account.#balance outside the class body does not return undefined. It fails to parse.

JavaScript
class Vault {
  #secret = 42;
}

try {
  eval("const v = new Vault(); v.#secret;");
} catch (error) {
  console.log(error.name + ": " + error.message);
}

try {
  eval("class Other { read(v) { return v.#secret; } }");
} catch (error) {
  console.log(error.name + ": " + error.message);
}
Text
SyntaxError: Private field '#secret' must be declared in an enclosing class
SyntaxError: Private field '#secret' must be declared in an enclosing class

The engine reports the error at parse time, before any code runs. Even another class in the same file cannot name #secret, because the name is scoped to the class that declares it. This is stronger than a naming convention and stronger than a closure, since the check happens statically.

Private methods and accessors

Methods, getters and setters can be private too. They are shared by all instances, and they are the right place for helper logic that callers must not use.

JavaScript
class Parser {
  #input;
  #position = 0;

  constructor(input) {
    this.#input = input;
  }

  #peek() {
    return this.#input[this.#position];
  }

  #advance() {
    return this.#input[this.#position++];
  }

  get #done() {
    return this.#position >= this.#input.length;
  }

  digits() {
    let text = "";
    while (!this.#done && /\d/.test(this.#peek())) {
      text += this.#advance();
    }
    return text;
  }
}

const parser = new Parser("123abc");

console.log(parser.digits());
console.log(typeof parser.peek, typeof parser.digits);
console.log(Object.getOwnPropertyNames(Parser.prototype));
Text
123
undefined function
[ 'constructor', 'digits' ]

The public digits() method uses three private helpers and a private getter. From outside, parser.peek does not exist, and the prototype lists only the constructor and the public method. A private method is not on the prototype, which is also why it cannot be overridden by a subclass: it belongs to the class that declared it.

Static privates

Privacy also applies to static members, which suits module-level state that belongs with a class.

JavaScript
class IdGenerator {
  static #next = 1;

  static #format(n) {
    return "id-" + String(n).padStart(4, "0");
  }

  static create() {
    return IdGenerator.#format(IdGenerator.#next++);
  }
}

console.log(IdGenerator.create(), IdGenerator.create());
console.log(Object.getOwnPropertyNames(IdGenerator));
Text
id-0001 id-0002
[ 'length', 'name', 'prototype', 'create' ]

The counter and the formatter are hidden from callers, and the class exposes one method. The code reads IdGenerator.#next and not this.#next, because a subclass calling create() would otherwise have this set to the subclass, which does not have the private static, and the access would throw.

Private members are not inherited

A subclass cannot see its parent's private members, and a subclass that declares a private name of its own does not clash with the parent's.

JavaScript
class Parent {
  #id = "parent";
  getParentId() {
    return this.#id;
  }
}

class Child extends Parent {
  #id = "child";
  getChildId() {
    return this.#id;
  }
}

const child = new Child();

console.log(child.getParentId(), child.getChildId());

try {
  eval("class Bad extends Parent { read() { return this.#id; } }");
} catch (error) {
  console.log(error.name + ": " + error.message);
}
Text
parent child
SyntaxError: Private field '#id' must be declared in an enclosing class

Two private fields named #id coexist on one object, one for each class. Neither shadows the other, because private names are scoped to the class body, not looked up through a chain. If a subclass needs access to something the parent holds, the parent has to expose it through a protected-by-convention method or a public getter.

The brand check

The expression #field in obj tests whether an object has that private field, which means it was constructed by that class. It never throws, so it is the safe way to validate an argument.

JavaScript
class Token {
  #value;

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

  static isToken(candidate) {
    return #value in candidate;
  }

  static unwrap(candidate) {
    if (!Token.isToken(candidate)) {
      throw new TypeError("not a Token");
    }
    return candidate.#value;
  }
}

const token = new Token("abc");

console.log(Token.isToken(token));
console.log(Token.isToken({ value: "abc" }));
console.log(Token.unwrap(token));

try {
  Token.unwrap({});
} catch (error) {
  console.log(error.name + ": " + error.message);
}

try {
  Token.isToken(null);
} catch (error) {
  console.log(error.name);
}
Text
true
false
abc
TypeError: not a Token
TypeError

A plain object that merely has a value property is not a token. The check is stricter than instanceof, since it cannot be fooled by Object.create(Token.prototype) or by changing a prototype, and it needs the object to have run the real constructor. Note that #value in null throws, as the last line shows, because the right side of in must be an object.

Where privacy breaks: proxies and wrong receivers

A private field belongs to the exact object that the constructor created. Wrapping that object in a Proxy creates a different object that has no private fields.

JavaScript
class Counter {
  #count = 0;
  increment() {
    return ++this.#count;
  }
}

const real = new Counter();
const proxy = new Proxy(real, {});

console.log(real.increment());

try {
  proxy.increment();
} catch (error) {
  console.log(error.name + ": " + error.message);
}

try {
  Counter.prototype.increment.call({});
} catch (error) {
  console.log(error.name + ": " + error.message);
}
Text
1
TypeError: Cannot read private member #count from an object whose class did not declare it
TypeError: Cannot read private member #count from an object whose class did not declare it

The method ran with this set to the proxy, which has no #count, so the read failed. The same error appears when a method is called on an arbitrary object. Reactive libraries that wrap state in proxies hit this, and the usual fix is to bind methods to the target, or to avoid private fields on objects that will be proxied. The post on Proxy and Reflect covers how to forward correctly.

Compared with the older patterns

Before #, three patterns approximated privacy. The _ prefix convention hides nothing. A closure over a variable inside a factory function gives real privacy, at the cost of one set of function objects per instance. A WeakMap keyed by the instance gives real privacy with shared methods, at the cost of an indirection on every access.

PatternReal privacyShared methodsVisible in debuggerSerializes
_name prefixNoYesYesYes
Closure in a factoryYesNoHiddenNo
WeakMap per fieldYesYesHiddenNo
#nameYesYesHidden, shown in some toolsNo

Private fields combine the good parts: real privacy and shared methods. Their cost is the proxy limit and the lack of inheritance, and the fact that tests cannot reach them, which is a feature if you test through the public surface.

Testing a class with private state

Private fields cannot be read from a test, and that is the point: the tests should exercise the public surface and let the private state follow. A good test of the Account class checks the behavior that depends on the hidden balance, including the failure path, and never reaches for the field.

JavaScript
import { test } from "node:test";
import assert from "node:assert/strict";

class Account {
  #balance = 0;
  deposit(amount) {
    if (amount <= 0) throw new RangeError("amount must be positive");
    this.#balance += amount;
  }
  get balance() {
    return this.#balance;
  }
}

test("deposits add to the balance", () => {
  const account = new Account();
  account.deposit(30);
  account.deposit(12);
  assert.equal(account.balance, 42);
});

test("a rejected deposit leaves the balance alone", () => {
  const account = new Account();
  account.deposit(10);
  assert.throws(() => account.deposit(-5), RangeError);
  assert.equal(account.balance, 10);
});

Run it with node --test on Node.js 24. If a test seems to need the private field, the class usually has a missing public method, or two classes tangled together. Resist exposing the field for the test, since that undoes the reason for making it private. See the post on getters and setters for the accessor pattern used here.

Where private fields are the wrong tool

If another module needs to read the data, it is not private, and a public getter is the honest design. If the object must be wrapped by a proxy, serialized by a generic tool or cloned with structuredClone(), private fields get in the way, and a plain property with a documented contract is better. And if you only want to discourage use, a _ prefix and a comment are cheaper and easier to debug.

Do not use privacy as a security boundary against code running in the same page or process. A debugger, a heap snapshot or a modified engine can read anything. It protects a class's invariants from accidental misuse, which is the real value.

The feature is defined in the specification under private names, and MDN's page on private elements lists the forms.

Also inPatterns
Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.