Sub topic 13
Computed Properties with Getters and Setters
This chapter assumes you know how to create objects and read their properties, how this works inside methods, and how to inspect a property with Object.getOwnPropertyDescriptor. All of these were covered in earlier chapters.
Up to now, every property you have written has been a data property. A data property stores a value in a slot. JavaScript also has accessor properties. An accessor property stores no value of its own. Instead it holds a function that runs when the property is read (a getter), and optionally a function that runs when the property is written (a setter). Code that uses the object reads and writes the property the same way it would a normal one. The difference is that the result can be computed on the fly.
Defining a getter and a setter
In an object literal, put get or set in front of a method definition:
const temp = {
celsius: 20,
get fahrenheit() {
return this.celsius * 9 / 5 + 32;
},
set fahrenheit(f) {
this.celsius = (f - 32) * 5 / 9;
}
};
console.log(temp.fahrenheit); // 68
temp.fahrenheit = 212; // calls the setter with f = 212
console.log(temp.celsius); // 100
console.log(temp.fahrenheit); // 212Notice that temp.fahrenheit is used without parentheses. The getter takes no arguments. The setter takes exactly one argument, which is the value on the right of the =. Inside both functions, this is the object the property was accessed on, just as it is in ordinary methods.
The only state is celsius. Because fahrenheit is derived from it every time, the two values cannot drift out of sync.
What the engine does on access
An accessor's descriptor has different fields from a data property's. It has get, set, enumerable, and configurable, but no value and no writable:
const temp = {
celsius: 20,
get fahrenheit() { return this.celsius * 9 / 5 + 32; }
};
console.log(Object.getOwnPropertyDescriptor(temp, "fahrenheit"));
// { get: [Function: get fahrenheit], set: undefined,
// enumerable: true, configurable: true }
Object.defineProperty(temp, "kelvin", {
get() { return this.celsius + 273.15; },
enumerable: true
});
console.log(temp.kelvin); // 293.15
console.log(Object.keys(temp)); // ["celsius", "fahrenheit", "kelvin"]If one descriptor mixes value or writable with get or set, Object.defineProperty throws a TypeError.
Common errors
Assigning to a getter-only property
When a property has a getter but no setter, assigning to it does nothing in sloppy mode. In strict mode the assignment throws:
"use strict";
const square = {
side: 3,
get area() { return this.side ** 2; }
};
try {
square.area = 100;
} catch (e) {
console.log(e instanceof TypeError); // true
}
console.log(square.area); // 9Infinite recursion in a setter
If a setter assigns to its own property name, it calls itself until the stack overflows. Store the real value under a different key, often called a backing field:
const user = {
_name: "",
get name() { return this._name; },
set name(value) {
// this.name = value; // would recurse forever
this._name = value.trim();
}
};
user.name = " Lin ";
console.log(user.name); // "Lin"Expensive or surprising getters
A reader assumes obj.x is cheap and has no side effects. Keep getters fast and free of side effects. If the work is heavy or changes state, write a normal method so the call site makes it visible.
When to use accessors
| Use an accessor when | Prefer a method or data property when |
|---|---|
| The value is derived from other properties | The value is independent state |
| You want to validate or normalize writes | The operation needs arguments |
| You are keeping an existing property's name while changing how it is computed | The work is slow or has side effects |
Exercise
What does this code log, and why? const box = { w: 2, h: 5, get area() { return this.w * this.h; } }; const copy = { ...box }; box.w = 10; console.log(box.area, copy.area);
Show answer
It logs 50 10. Spread reads each property, so it calls the getter once and stores its result (10) as a plain data property on copy. box.area still runs the getter, which now gives 10 * 5 = 50. copy.area is a fixed value that no longer tracks w.
Exercise
Add a setter for fullName to { first: "Ada", last: "Lovelace", get fullName() { return ${this.first} ${this.last}; } } so that assigning "Grace Hopper" updates first and last.
Show answer
Add: set fullName(value) { const [first, last] = value.split(" "); this.first = first; this.last = last; }. After obj.fullName = "Grace Hopper", obj.first is "Grace" and obj.last is "Hopper".