Sub topic 2
Private Fields with the # Syntax
This chapter assumes you know ES2015 class syntax, the this keyword, and how getters and setters work on object literals.
Private Fields
A private field is a class member whose name starts with #. Only code inside the class body can read or write it. If code outside the class mentions user.#email, you get a SyntaxError when the script is parsed, before any of it runs. Private fields do not appear in Object.keys and are left out of JSON.stringify.
Validating and Computing Values Through Accessors
A common pattern pairs a public accessor with a private field. The setter checks and cleans each value, and the getter returns the stored result. The constructor assigns through the setter, so new objects get the same validation. A getter can also compute a value from private state instead of storing it.
class User {
#email;
constructor(email) {
this.email = email; // runs the setter
}
get email() {
return this.#email;
}
set email(value) {
if (typeof value !== 'string' || !value.includes('@')) {
throw new TypeError('Invalid email');
}
this.#email = value.trim().toLowerCase();
}
get domain() {
return this.#email.split('@')[1]; // computed, never stored
}
}
const user = new User('[email protected]');
console.log(user.email); // '[email protected]'
console.log(user.domain); // 'example.com'
console.log(JSON.stringify(user)); // '{}'Private Methods and Private Accessors
Methods and accessors can be private too. They hold internal helpers that callers should never depend on.
class Counter {
#count = 0;
get #label() {
return `count is ${this.#count}`;
}
#log() {
console.log(this.#label);
}
increment() {
this.#count++;
this.#log();
}
}
new Counter().increment(); // count is 1Static Getters and Setters
A static accessor lives on the class itself, not on its instances. You use it for class-level settings.
let level = 'info';
class Logger {
static get level() {
return level;
}
static set level(value) {
if (!['debug', 'info', 'warn'].includes(value)) {
throw new RangeError(`Unknown level: ${value}`);
}
level = value;
}
}
Logger.level = 'debug';
console.log(Logger.level); // 'debug'
console.log(new Logger().level); // undefined| Common error | Cause |
|---|---|
| `SyntaxError` on `obj.#x` | Private name used outside the class body |
| Invalid value accepted at creation | Constructor wrote `this.#x` directly instead of going through the setter |
| `undefined` from `instance.level` | Static accessor read from an instance |
Exercise
In the User class, the constructor is changed to this.#email = email;. What happens with new User('not-an-email'), and why?
Show answer
No error is thrown, and the raw string is stored without trimming or lowercasing. Assigning to this.#email directly skips the email setter, so neither validation nor normalization runs.