Sub topic 13
Common Pitfalls and How to Avoid Them
This chapter assumes you know how to write getters and setters in object literals and classes, and how private # fields, brand checks, and subclass accessors work. Each section below shows a bug that comes up in real code, explains why the engine behaves that way, and gives a fix you can reuse.
Recursive Setters
The most common accessor bug is a setter that assigns to its own property name.
class Broken {
set name(value) {
this.name = value; // calls the setter again
}
}
// new Broken().name = 'x'; // RangeError: Maximum call stack size exceededWhen the engine runs this.name = value, it looks up name and finds the accessor on Broken.prototype. It then calls the setter again, and the setter makes the same assignment, so the calls never stop. A getter that reads this.name inside itself loops the same way.
The fix is to store the value under a different key, called a backing field. A private field is the best choice because nothing outside the class can bypass the accessor to reach it.
class Fixed {
#name = '';
get name() {
return this.#name;
}
set name(value) {
this.#name = String(value);
}
}
const f = new Fixed();
f.name = 'x';
console.log(f.name); // 'x'Assigning to a Getter-Only Property
If an accessor has a getter and no setter, assigning to it fails. What happens on failure depends on the code that makes the assignment, not on the code that defined the property.
| Code doing the assignment | Result of `obj.prop = value` with no setter |
|---|---|
| Strict mode (modules, class bodies, `'use strict'`) | Throws `TypeError` |
| Sloppy-mode script | Silently ignored, value unchanged |
The silent case is the dangerous one. A non-module script can "set" a read-only value, and nothing tells you it didn't change. Use ES modules or 'use strict' so these bugs throw. If callers really need to change the value, give them a setter or an explicit method such as deposit(amount), and don't let them write to the property directly.
Overriding Only Half of an Accessor
The getter and setter for one name make up a single accessor property. If a subclass defines only a getter, it creates a new accessor whose set is undefined. That new accessor shadows the whole inherited one.
class Base {
#value = 1;
get value() { return this.#value; }
set value(v) { this.#value = v; }
}
class Derived extends Base {
get value() { return super.value * 10; }
}
'use strict';
const d = new Derived();
try {
d.value = 5; // Derived.prototype.value has no setter
} catch (err) {
console.log(err instanceof TypeError); // true in strict code
}The 'use strict' line in the middle of the file has no effect, because a directive only counts at the very top of a script or function. The TypeError happens because this example is meant to run as a module or inside strict code. In a sloppy script the assignment is silently ignored. In both cases Base's setter never runs.
The fix is to override both halves, and to use super to forward the half you don't want to change:
class Base {
#value = 1;
get value() { return this.#value; }
set value(v) { this.#value = v; }
}
class Derived extends Base {
get value() { return super.value * 10; }
set value(v) { super.value = v; }
}
const d = new Derived();
d.value = 5;
console.log(d.value); // 50Class Fields That Shadow Inherited Accessors
Class field declarations use define semantics. The engine creates an own data property on the instance with Object.defineProperty, so it never makes an assignment. As a result, a field declared in a subclass skips the setter it inherits from its parent.
class Base {
#name = '';
get name() { return this.#name; }
set name(v) { this.#name = String(v).trim(); }
}
class Derived extends Base {
name = ' Ada '; // defines an own data property
}
const d = new Derived();
console.log(d.name); // ' Ada ' (setter never ran)
console.log(Object.keys(d)); // [ 'name' ]The instance now has its own name data property, which hides the validated accessor permanently. Every later assignment also skips the setter. To fix it, make a real assignment in the constructor:
class Derived extends Base {
constructor() {
super();
this.name = ' Ada '; // goes through Base's setter
}
}
console.log(new Derived().name); // 'Ada'TypeScript users may see this as a behavior change when useDefineForClassFields is enabled. That flag is on by default when targeting ES2022 or later.
Accessors and Private Fields Disappear When You Serialize
JSON.stringify, object spread, Object.assign, and structuredClone work only with own, enumerable, string-keyed properties. Class accessors live on the prototype, and private fields are not properties at all. So a well-encapsulated object usually serializes as empty.
class Temperature {
#celsius;
constructor(c) { this.#celsius = c; }
get celsius() { return this.#celsius; }
get fahrenheit() { return this.#celsius * 9 / 5 + 32; }
}
const t = new Temperature(100);
console.log(JSON.stringify(t)); // '{}'
console.log({ ...t }); // {}
console.log(structuredClone(t)); // {} (a plain object; the class and #celsius are gone)Own accessors on object literals behave differently, and that difference causes problems too. Spread and Object.assign call the getter and copy the result as a plain data property. You get a snapshot, and it stops updating:
const temperature = {
celsius: 20,
get fahrenheit() { return this.celsius * 9 / 5 + 32; }
};
const copy = { ...temperature };
copy.celsius = 100;
console.log(copy.fahrenheit); // 68 (frozen at copy time)
console.log(Object.getOwnPropertyDescriptor(copy, 'fahrenheit').get); // undefinedObject.assign(target, source) also triggers setters on the target, so copying into an object that has accessors runs their validation, and that validation can throw.
For JSON, the fix is a toJSON method that lists exactly what to output:
class Temperature {
#celsius;
constructor(c) { this.#celsius = c; }
get celsius() { return this.#celsius; }
get fahrenheit() { return this.#celsius * 9 / 5 + 32; }
toJSON() {
return { celsius: this.celsius, fahrenheit: this.fahrenheit };
}
static fromJSON(data) {
return new Temperature(data.celsius);
}
}
const json = JSON.stringify(new Temperature(100));
console.log(json); // '{"celsius":100,"fahrenheit":212}'
console.log(Temperature.fromJSON(JSON.parse(json)).fahrenheit); // 212A static fromJSON (or a matching constructor) is the other half of the fix. Parsing gives you back a plain object, and only the class can rebuild the private state.
Reading a Private Field on the Wrong Object
Reading obj.#x when obj was not built by the class throws a TypeError. It does not return undefined. This often happens in static helpers, comparison methods such as equals(other), and callbacks that receive arbitrary values.
class Point {
#x;
constructor(x) { this.#x = x; }
equals(other) {
return #x in other && this.#x === other.#x;
}
}
console.log(new Point(1).equals(new Point(1))); // true
console.log(new Point(1).equals({ x: 1 })); // false, no TypeErrorPut the brand check first, so the && short-circuits before the engine tries to read the field. Note that #x in other itself throws if other is a primitive such as null or 42. Guard with typeof other === 'object' && other !== null when primitives are possible.
Proxies Break Private Fields
A Proxy with an empty handler looks transparent, but it is a separate object that has no private fields. When you read proxied.v, the default get behavior calls the getter with this set to the proxy. The getter then reads this.#v on the proxy and throws.
Methods fail the same way, because proxied.method() also calls them with this set to the proxy. The usual fix is to run getters against the target and bind methods to the target:
class Box {
#v = 42;
get v() { return this.#v; }
double() { return this.#v * 2; }
}
const target = new Box();
const proxied = new Proxy(target, {
get(t, prop) {
const value = Reflect.get(t, prop, t); // receiver = target, not proxy
return typeof value === 'function' ? value.bind(t) : value;
}
});
console.log(proxied.v); // 42
console.log(proxied.double()); // 84This fix has a cost. Code inside the class now sees the real target, so the proxy can't intercept property accesses that the class makes on itself. Frameworks that make state reactive through Proxies (Vue's reactivity system, MobX, and similar) run into this limit. If you depend on such a library, check its documentation for how it handles classes with # fields. Some of these libraries recommend plain objects or underscore properties instead.
Getters That Do Too Much
People read a getter as a cheap, side-effect-free lookup. Several things go wrong when that isn't true:
- Debuggers and
console.logpreviews may call getters, so a getter with side effects can change state while you are just inspecting it. - Code like
for (...) total += obj.expensivereruns the computation on every read. - A getter that throws makes ordinary-looking property access fail far from the cause.
If the value is expensive and never changes, cache it the first time it is read by defining an own data property that shadows the prototype getter:
function expensiveCompute() {
console.log('computing...');
return 42;
}
class Report {
get summary() {
const value = expensiveCompute();
Object.defineProperty(this, 'summary', {
value,
writable: false,
enumerable: false,
configurable: true
});
return value;
}
}
const r = new Report();
console.log(r.summary); // computing... then 42
console.log(r.summary); // 42 (own data property now)If the work has side effects or can fail, make it a method such as loadSummary() so the call site shows that work is happening.
Quick Reference
| Pitfall | Symptom | Fix |
|---|---|---|
| Setter assigns its own name | `RangeError` stack overflow | Store in a `#backing` field |
| Getter-only, assigned in sloppy code | Value silently unchanged | Use modules or strict mode; add a setter or method |
| Subclass overrides only the getter | Assignments throw or are ignored | Override both; forward with `super.value` |
| Subclass field with same name as accessor | Validation skipped, own data property | Assign in the constructor |
| `JSON.stringify` / spread on class instance | `{}` or missing values | `toJSON` plus `fromJSON` |
| Spread of a literal with getters | Stale snapshot values | Copy deliberately, or rebuild the object |
| `other.#x` on a foreign object | `TypeError` | Check `#x in other` first |
| Proxy around class instance | `TypeError` in getters and methods | `Reflect.get(t, prop, t)` and bind methods |
| Expensive or side-effecting getter | Slow loops, surprise state changes | Cache lazily or use a method |
Exercise
A class Config has get port() and set port(v) that validates the value is between 1 and 65535, storing it in #port. A subclass declares class DevConfig extends Config { port = 99999; }. What does new DevConfig().port return, and why? How would you fix it?
Show answer
It returns 99999. The class field uses define semantics, so it creates an own data property named port on the instance. That property shadows the inherited accessor, and the validating setter never runs. To fix it, remove the field and assign in the constructor (constructor() { super(); this.port = 99999; }). The assignment goes through the setter, which then rejects the invalid value.
Exercise
You have class Money { #cents; constructor(c) { this.#cents = c; } get dollars() { return this.#cents / 100; } }. Calling JSON.stringify(new Money(250)) returns '{}'. Explain why, and write the smallest change that makes it output '{"cents":250}'.
Show answer
JSON.stringify only includes own enumerable properties. The dollars getter lives on Money.prototype, and #cents is a private field, not a property, so neither one appears. Add a method to the class: toJSON() { return { cents: this.#cents }; }.
Exercise
Wrapping an instance of a class whose getter reads this.#secret in new Proxy(instance, {}) makes reading the getter throw a TypeError. Why does this happen, and what should the Proxy's get trap do instead?
Show answer
The default get behavior calls the getter with the proxy as the receiver, so this is the proxy. The proxy has no #secret private field, so reading it throws. The trap should call Reflect.get(target, prop, target) so getters run with this set to the real instance. It should also bind any function values to target, so that methods that read private fields work too.