Sub topic 7
Computed Properties with Getters and Setters
This chapter assumes you can write a class with a constructor, instance methods, and public fields. You should also know that methods live on the class's prototype. You will learn how accessor properties work, where JavaScript stores them, and the common mistakes they cause.
What an Accessor Property Is
JavaScript objects have two kinds of properties. A data property holds a value. An accessor property holds a pair of functions. The get function runs when you read the property, and the set function runs when you assign to it. To the code using the object, both kinds look the same: you write obj.prop with no parentheses.
In a class body, you declare accessors with the get and set keywords:
class Temperature {
constructor(celsius) {
this.celsius = celsius;
}
get fahrenheit() {
return this.celsius * 9 / 5 + 32;
}
set fahrenheit(value) {
this.celsius = (value - 32) * 5 / 9;
}
}
const t = new Temperature(25);
console.log(t.fahrenheit); // 77
t.fahrenheit = 212;
console.log(t.celsius); // 100Only celsius is stored. fahrenheit is computed from it every time you read it, so the two values can never disagree. A getter takes no parameters. A setter takes exactly one, which is the value on the right side of the assignment.
Where Accessors Live
Accessors work like methods. They are defined once on Temperature.prototype, and instances do not get their own copy. You can check this with the property descriptor:
class Temperature {
constructor(celsius) {
this.celsius = celsius;
}
get fahrenheit() {
return this.celsius * 9 / 5 + 32;
}
set fahrenheit(value) {
this.celsius = (value - 32) * 5 / 9;
}
}
const t = new Temperature(100);
const desc = Object.getOwnPropertyDescriptor(Temperature.prototype, 'fahrenheit');
console.log(typeof desc.get, typeof desc.set); // function function
console.log(desc.enumerable); // false
console.log(Object.hasOwn(t, 'fahrenheit')); // false
console.log(Object.keys(t)); // [ 'celsius' ]
console.log(JSON.stringify(t)); // {"celsius":100}Reading t.fahrenheit follows the prototype chain. JavaScript finds the accessor on the prototype and calls its getter with this set to t, the object you started the lookup from.
Some practical results of this design:
- Accessors are non-enumerable and are not own properties.
Object.keys, spread ({ ...t }), andJSON.stringifyall skip them. - If you want computed values in JSON, add a
toJSON()method that returns them explicitly. - Any own property with the same name hides the accessor. The field gotcha later in this chapter comes from this rule.
Validating Input in a Setter
The most common reason to write a setter is to check values before storing them. The setter needs somewhere to put the real value. That place is called a backing property. In this chapter the backing property uses an underscore prefix by convention. A later chapter replaces it with a truly private #field.
class Account {
constructor(owner) {
this.owner = owner; // runs the setter below
}
get owner() {
return this._owner;
}
set owner(value) {
if (typeof value !== 'string' || value.trim() === '') {
throw new TypeError('owner must be a non-empty string');
}
this._owner = value.trim();
}
}
const acct = new Account(' Ada ');
console.log(acct.owner); // 'Ada'
try {
acct.owner = '';
} catch (err) {
console.log(err.message); // 'owner must be a non-empty string'
}The constructor's this.owner = owner goes through the setter, so validation also applies when the object is created. You don't need a separate check in the constructor.
Read-Only Properties: Getter Without a Setter
If you define only a getter, the property is read-only. What happens when someone assigns to it depends on the strictness of the code doing the assignment, not of the class:
'use strict';
class Circle {
constructor(radius) {
this.radius = radius;
}
get area() {
return Math.PI * this.radius ** 2;
}
}
const c = new Circle(2);
console.log(c.area.toFixed(2)); // '12.57'
try {
c.area = 10;
} catch (err) {
console.log(err instanceof TypeError); // true
}ES modules and class bodies are always strict, so the assignment throws there. In a classic non-module script without 'use strict', the assignment is silently ignored, and that can hide bugs. A setter-only property, which has no getter, reads as undefined. That is rarely what you want.
Common Errors
Infinite recursion in a setter
If a setter assigns to its own name, it calls itself:
class Broken {
set name(value) {
this.name = value; // calls this setter again
}
}
try {
new Broken().name = 'x';
} catch (err) {
console.log(err instanceof RangeError); // true: Maximum call stack size exceeded
}A getter that returns this.name from inside get name() fails the same way. The fix is always to store the value under a different name, such as _name or #name.
A field with the same name shadows the accessor
Public fields are created on the instance with define semantics, much like Object.defineProperty, and not by assignment. As a result, a field never triggers a setter, and the own property it creates hides any accessor on the prototype:
class Widget {
size = 10;
get size() {
return 999;
}
}
console.log(new Widget().size); // 10, the getter is dead codeThis problem is easy to miss when the accessor and the field are in different classes:
class Base {
get color() {
return this._color;
}
set color(value) {
console.log('setter ran');
this._color = value.toLowerCase();
}
}
class Child extends Base {
color = 'RED'; // defines an own property; Base's setter never runs
}
const ch = new Child();
console.log(ch.color); // 'RED', not lowercased
console.log(Object.hasOwn(ch, 'color')); // trueTo make the parent's setter run, assign in the constructor. Assignment uses the prototype chain, but a field definition does not:
class Base {
get color() {
return this._color;
}
set color(value) {
this._color = value.toLowerCase();
}
}
class FixedChild extends Base {
constructor() {
super();
this.color = 'RED'; // goes through Base's setter
}
}
console.log(new FixedChild().color); // 'red'Defining only half a pair in a subclass
If a subclass overrides only the getter, the property on the subclass prototype has a getter and no setter. Lookup stops at the first prototype that has the property, so the parent's setter is hidden and assignment fails. When you override one half of an accessor, define both halves. To keep the parent's behavior, the override can call super.prop and super.prop = value, which are covered with super in a later chapter.
Lazy, Cached Getters
A getter runs on every read. For an expensive computation, the getter can replace itself with an own data property the first time it runs:
class Report {
constructor(rows) {
this.rows = rows;
}
get total() {
console.log('computing');
const value = this.rows.reduce((sum, n) => sum + n, 0);
Object.defineProperty(this, 'total', { value, writable: false });
return value;
}
}
const r = new Report([1, 2, 3]);
console.log(r.total); // logs 'computing', then 6
console.log(r.total); // 6, served from the own propertyThe own property shadows the prototype getter, which is the same rule that caused the field gotcha. The trade-off is staleness: if rows changes later, total does not update. Use this pattern only for values that are fixed once computed.
Computed Names and Static Accessors
Accessor names can be computed with brackets, and they can be static:
const key = 'label';
class Tag {
static get kind() {
return 'html-tag';
}
constructor(text) {
this._text = text;
}
get [key]() {
return `<${this._text}>`;
}
}
console.log(new Tag('div').label); // '<div>'
console.log(Tag.kind); // 'html-tag'Choosing Between a Getter, a Method, and a Data Property
| Situation | Use |
|---|---|
| Plain stored value with no rules | Data property or public field |
| Cheap value derived from other state | Getter |
| Stored value that must be validated or normalized | Getter and setter with a backing property |
| Work that is slow, has side effects, or takes arguments | Method |
| Expensive value that never changes after first use | Lazy getter that caches itself |
Readers of obj.prop expect it to be fast and free of side effects. If a getter makes network calls, mutates state, or can throw for ordinary reasons, make it a method so the call site shows that work is happening.
Exercise
A class declares items = []; as a field and also get count() { return this.items.length; }. A subclass declares the field count = 0;. What does new Sub().count return after pushing two items, and why?
Show answer
It returns 0. The subclass field defines an own data property named count on the instance, and that own property shadows the getter on the parent prototype, so the getter never runs.
Exercise
Write a Rectangle class whose width setter throws a RangeError for negative numbers, whose constructor validates through that setter, and which exposes a read-only area getter. Use the height passed to the constructor directly.
Show answer
class Rectangle { constructor(w, h) { this.width = w; this.height = h; } get width() { return this.width; } set width(v) { if (v < 0) throw new RangeError('width must be >= 0'); this.width = v; } get area() { return this._width * this.height; } }. Here new Rectangle(3, 4).area is 12, and new Rectangle(-1, 4) throws a RangeError.
Exercise
Why does JSON.stringify(new Temperature(25)) output {"celsius":25} without fahrenheit, and how would you include it?
Show answer
fahrenheit is a non-enumerable accessor on Temperature.prototype, not an own enumerable property, so JSON.stringify skips it. Add a method toJSON() { return { celsius: this.celsius, fahrenheit: this.fahrenheit }; } to include it.