Sub topic 5
Private Fields with the # Syntax
This chapter assumes you are comfortable with ES2015 class syntax, extends and super(), the this keyword, and the class getters and setters from the previous chapter. Every example runs as-is in Node.js 16+ or any current browser. Private class fields became standard in ES2022.
Until now, every property you defined, accessor or data, could be read and overwritten by any code holding a reference to the object. A getter can make a value look read-only, but the value it reads has to be stored somewhere, and that storage location was public. Private fields close that gap. A private field is a per-instance slot whose name starts with #. Only code written inside the class body that declares it can reach it.
Declaring and Using a Private Field
A private field has to be declared in the class body before any method uses it. The declaration can carry an initializer, or it can be left bare, in which case the field starts as undefined.
class Thermostat {
#target = 20; // private field with an initializer
#history; // declared without one: starts as undefined
constructor() {
this.#history = [];
}
get target() {
return this.#target;
}
set target(value) {
this.#history.push(this.#target);
this.#target = value;
}
get previous() {
return this.#history.at(-1);
}
}
const t = new Thermostat();
t.target = 22;
console.log(t.target); // 22
console.log(t.previous); // 20
// console.log(t.#target); // SyntaxError: outside the class bodyHere are the rules this example shows:
- The
#belongs to the name.#targetandtargetare unrelated, so a class can have a public accessortargetbacked by a private field#targetwithout a clash. You will use this pairing constantly. - Access always goes through a dot:
this.#target. There is no bracket form.this['#target']refers to an ordinary property whose string key happens to start with#. - The commented-out last line is a SyntaxError, not a runtime error. The engine rejects the whole script at parse time, so if you uncomment it, none of the earlier lines run either.
Hard Privacy: What Outside Code Can and Cannot See
Private fields are not properties in the usual sense. They are absent from every reflection API, so serializers, loggers, and other libraries cannot find them, and neither can an attacker.
class Token {
#secret = 'abc123';
label = 'api';
}
const tok = new Token();
console.log(Object.keys(tok)); // [ 'label' ]
console.log(Reflect.ownKeys(tok)); // [ 'label' ]
console.log(Object.getOwnPropertyNames(tok)); // [ 'label' ]
console.log(JSON.stringify(tok)); // {"label":"api"}
console.log(tok['#secret']); // undefined
tok['#secret'] = 'oops'; // a normal string-keyed property
console.log(Object.keys(tok)); // [ 'label', '#secret' ]The last two lines catch people out. Writing tok['#secret'] neither reads nor overwrites the private field. It creates a public property that sits next to the private one, and the class methods keep reading the real #secret.
Privacy in this sense means the language enforces it. Developer tools such as the Chrome console do display private fields while you debug, because the inspector is privileged. Ordinary JavaScript code never gets that access.
Accessing Private Fields on Other Instances
Because privacy is scoped to the class body, methods that compare or combine two instances can read each other's private state directly:
class Money {
#cents;
constructor(cents) {
this.#cents = cents;
}
get cents() {
return this.#cents;
}
equals(other) {
return this.#cents === other.#cents;
}
add(other) {
return new Money(this.#cents + other.#cents);
}
}
const a = new Money(150);
const b = new Money(250);
console.log(a.add(b).cents); // 400
console.log(a.equals(new Money(150))); // true
try {
a.equals({ cents: 150 }); // looks like Money, but has no #cents
} catch (err) {
console.log(err instanceof TypeError); // true
}Reading other.#cents on an object that was not built by Money throws a TypeError. Ordinary properties behave differently: a missing one quietly evaluates to undefined. Private fields fail loudly, which is often what you want. A later chapter shows the #cents in obj brand check, which tests for the field without throwing.
How the Engine Resolves `obj.#x`
Every private-field access passes two separate checks, one at parse time and one at run time.
The parse-time check is lexical. It looks at the source code that physically encloses the access. The run-time check looks at the object. Keep both checks in mind and most private-field errors become predictable.
Each Class Gets Its Own Names
A private name belongs to the class that declares it, not to its spelling. Two classes that both declare #id have two unrelated slots:
class Order {
#id;
constructor(id) { this.#id = id; }
static idOf(o) { return o.#id; }
}
class Invoice {
#id;
constructor(id) { this.#id = id; }
}
const inv = new Invoice(7);
try {
Order.idOf(inv); // Invoice's #id is not Order's #id
} catch (err) {
console.log(err instanceof TypeError); // true
}The same rule covers inheritance. A subclass cannot reach its parent's private fields. If a Derived class body contains this.#id and does not declare #id itself, that is a SyntaxError, even when the parent declares #id. If Derived does declare its own #id, the instance ends up holding two separate slots, one per class. The chapter on subclasses covers how to share state across a hierarchy through protected-style accessors.
Rules the Parser Enforces
Private fields are deliberately static. Their shape is fixed when the class is defined, and the engine rejects anything that would change it later. Every line in the table below is a SyntaxError.
| Code inside a class body | Why it is rejected |
|---|---|
| `this.#y = 1;` with no `#y;` declaration | Private names must be declared up front |
| `#a; #a;` | Duplicate private name |
| `delete this.#a;` | Private fields cannot be deleted |
| `this.#[name]` | No computed private names |
| `#constructor;` | `#constructor` is reserved |
| `const o = { #a: 1 };` (anywhere) | Object literals cannot have private names |
Some things are allowed: optional chaining (obj?.#a returns undefined when obj is nullish), compound assignment (this.#count += 1), destructuring targets ([this.#a, this.#b] = pair), and increment operators (this.#count++).
Initialization Order and the Constructor Trap
Private fields are installed on the instance at a specific moment:
- In a base class, field initializers run, top to bottom, just before the constructor body starts.
- In a derived class, they run immediately after
super()returns.
An initializer can therefore refer to fields declared above it:
class Rect {
#w = 3;
#h = 4;
#area = this.#w * this.#h; // earlier fields already exist
get area() { return this.#area; }
}
console.log(new Rect().area); // 12The second rule creates a real trap. While the parent constructor runs, the child's private fields do not exist yet. If the parent calls a method that the child overrides, and that method reads a child private field, the call throws:
class Base {
constructor() {
this.describe(); // calls the subclass override
}
describe() {}
}
class Child extends Base {
#name = 'child';
describe() {
console.log(this.#name);
}
}
try {
new Child();
} catch (err) {
console.log(err instanceof TypeError); // true: #name not installed yet
}With a public field, this.name would have quietly returned undefined at that point. With a private field the bug surfaces as an error. To fix it, avoid calling overridable methods from constructors, or move that work into an explicit init() step that runs after construction.
Common Errors at a Glance
| Symptom | Cause | Fix |
|---|---|---|
| `SyntaxError: Private field '#x' must be declared in an enclosing class` | Missing declaration, or access from outside or from a subclass | Declare `#x;` in this class, or expose a getter |
| `TypeError: Cannot read private member #x from an object whose class did not declare it` | Wrong receiver: a plain object, another class, a lost `this`, or a field not installed yet | Check the receiver, bind callbacks, avoid overridable calls in constructors |
| Private value missing from `JSON.stringify` output | Private fields are not properties | Add a `toJSON()` method that returns what you want serialized |
| A `#name` key appears in `Object.keys` | Bracket access `obj['#name']` created a public property | Use `this.#name`, and only inside the class |
When to Reach for a Private Field
Use a private field for state that the class must keep consistent: counters, caches, validated values, handles to resources. Pair it with a public getter when outside code needs to read the value, and with a setter when it needs to write the value under the class's rules. The next chapter builds on this pairing to validate and normalize assigned values. Keep using public fields for plain data records that you want to be enumerable, spreadable, and serializable.
Exercise
Will this script print anything? Explain which check fails and when. class A { #v = 1; } class B extends A { read() { return this.#v; } } console.log('start');
Show answer
It prints nothing. B's body references #v, but no class body enclosing that code declares #v. A's declaration belongs to A, not to B. The parser therefore rejects the script with a SyntaxError before any line runs, including console.log('start').
Exercise
Write a class Stack with a private #items array and push, pop, and a size getter. Make JSON.stringify(stack) produce {"size":N}. What does Object.keys(new Stack()) return?
Show answer
class Stack { #items = []; push(x) { this.#items.push(x); return this; } pop() { return this.#items.pop(); } get size() { return this.#items.length; } toJSON() { return { size: this.size }; } }. Object.keys returns [] because #items is not a property, and size is an accessor defined on Stack.prototype, not an own property. JSON.stringify calls toJSON, so new Stack().push(1).push(2) serializes to {"size":2}.
Exercise
Given class Money above, why does [a, b].map(a.equals) throw, and how would you fix it?
Show answer
map calls the extracted function with this set to undefined, because class bodies are strict mode. Reading this.#cents on undefined throws a TypeError. Fix it with [a, b].map(x => a.equals(x)) or with a.equals.bind(a).