Sub topic 5
Private Fields with the # Syntax
This chapter assumes you know ES2015 class syntax, how this works inside methods, and how getters and setters are declared in classes (covered in the previous chapter).
A private field is a property whose name starts with #. It can be read and written only by code written inside the class body that declares it. No code outside the class can reach the field: not property access, not Object.keys, not JSON.stringify. The language enforces this, so privacy here does not depend on developers following a naming convention.
Declaring and Using a Private Field
You must declare every private field in the class body before you use it. A declaration can include an initializer, and the initializer runs once for each new instance.
class Thermostat {
#target = 20;
#history = [];
setTarget(value) {
this.#history.push(this.#target);
this.#target = value;
}
undo() {
if (this.#history.length > 0) {
this.#target = this.#history.pop();
}
}
get target() {
return this.#target;
}
}
const t = new Thermostat();
t.setTarget(23);
t.setTarget(25);
t.undo();
console.log(t.target); // 23
console.log(Object.keys(t)); // []
console.log(JSON.stringify(t)); // '{}'
console.log(t['#target']); // undefined
// console.log(t.#target); // SyntaxError outside the class bodyHere, the public getter target lets outside code read the value, and nothing outside the class can write to it directly. Note that t['#target'] looks up an ordinary string key named "#target", which does not exist. A private name is not a string, so bracket notation can never reach it.
The Rules the Engine Enforces
| Rule | What happens if you break it |
|---|---|
| The field must be declared in the class body | `this.#x = 1` without a declaration is a SyntaxError |
| Access is only allowed inside the class body | `obj.#x` written outside the class is a SyntaxError |
| The object must actually have the field | Reading `#x` on an object without it throws a TypeError |
| The same name cannot be declared twice | Declaring the same private name twice is a SyntaxError |
| Private fields cannot be deleted | `delete this.#x` is a SyntaxError |
| Private names cannot be computed | `this[#x]` and `this['#x']` do not reach the field |
Most of these errors are SyntaxErrors. The parser rejects the code before any of it runs, so your tooling catches typos such as this.#tagret straight away.
Privacy Is Per Class, Not Per Instance
Methods of a class can read private fields on any instance of that class, not only on this. This makes comparison methods simple to write:
class Money {
#cents;
constructor(cents) {
this.#cents = cents;
}
equals(other) {
return this.#cents === other.#cents;
}
}
console.log(new Money(500).equals(new Money(500))); // true
console.log(new Money(500).equals(new Money(250))); // falseIf other is not a Money instance, other.#cents throws a TypeError. A later chapter shows how to test for the field safely with #cents in other.
Each class also has its own set of private names. A subclass that declares its own #cents gets a separate field that does not clash with the parent's field. The subclass cannot see the parent's private fields at all, so it must use the parent's public or protected-style API.
Common Errors
- Forgetting
this.: writing#count++alone is a SyntaxError. Always writethis.#count. - Expecting private fields in logs or JSON output. They are left out of
JSON.stringify,Object.keys, and spread copies such as{ ...obj }. Browser devtools may show them, but your code cannot enumerate them. - Assigning a field you never declared. Unlike public properties, private fields cannot be added on the fly.
Exercise
A class declares #id = 0; and has a method copyFrom(src) { this.#id = src.#id; }. What happens when you call a.copyFrom({ id: 5 }), and why?
Show answer
It throws a TypeError. The method is inside the class body, so the code parses without error. But the plain object { id: 5 } was not built by the class, so it has no #id field. Its public id property is unrelated to the private name.
Exercise
Why does obj['#secret'] return undefined even inside the class that declares #secret?
Show answer
Bracket notation looks up a string key, and '#secret' is an ordinary string that does not exist on the object. Private names are not strings and can only be reached with the literal obj.#secret syntax.