Sub topic 13
Computed Properties with Getters and Setters
This chapter assumes you already know how to read and write properties, how this is bound in methods, and what property descriptors such as writable and enumerable mean. It also uses Object.create and the prototype chain from earlier chapters.
A data property stores a value. An accessor property stores no value at all. It holds a pair of functions instead: a get function that runs when the property is read, and a set function that runs when the property is written. From the outside, obj.area looks like an ordinary property read, but code runs every time. That makes accessors useful for derived values, validation, and lazy computation. Because they look like plain properties, they also cause some surprising bugs, which this chapter covers.
Defining Accessors in Object Literals
Inside an object literal, put get or set before a method-style definition:
const user = {
first: "Ada",
last: "Lovelace",
get fullName() {
return `${this.first} ${this.last}`;
},
set fullName(value) {
const [first, ...rest] = value.split(" ");
this.first = first;
this.last = rest.join(" ");
}
};
console.log(user.fullName); // "Ada Lovelace"
user.fullName = "Grace Brewster Hopper";
console.log(user.first); // "Grace"
console.log(user.last); // "Brewster Hopper"
console.log(Object.getOwnPropertyDescriptor(user, "fullName"));
// { get: [Function: get fullName], set: [Function: set fullName],
// enumerable: true, configurable: true }You never call fullName() with parentheses. Reading user.fullName calls the getter with this set to user. Assigning to it calls the setter with the assigned value as its only argument. The setter's return value is ignored, and the assignment expression still evaluates to the right-hand side.
The descriptor shows how accessor properties differ from data properties. An accessor descriptor has get, set, enumerable, and configurable. It never has value or writable. A descriptor that mixes the two kinds, such as { get() {}, value: 1 }, makes Object.defineProperty throw a TypeError.
What Happens on Read and Write
When JavaScript evaluates obj.prop, it finds the property by walking the prototype chain, as it does for any lookup. If the property it finds is an accessor, JavaScript calls the getter with this bound to the original object (obj), even when the accessor lives on a prototype.
Writes follow a similar path, with one asymmetry. If the chain contains an accessor with a setter, the setter runs with this set to obj, and no own property is created. If it contains an accessor without a setter, the write fails.
Getter-Only and Setter-Only Properties
You can define just one half of the pair, and each half has its own behavior when the other is missing:
| Defined | Reading | Writing (sloppy mode) | Writing (strict mode) |
|---|---|---|---|
| `get` only | Runs the getter | Silently ignored | `TypeError` |
| `set` only | Returns `undefined` | Runs the setter | Runs the setter |
| Both | Runs the getter | Runs the setter | Runs the setter |
"use strict";
const circle = {
radius: 2,
get area() {
return Math.PI * this.radius ** 2;
}
};
console.log(circle.area.toFixed(2)); // "12.57"
try {
circle.area = 10;
} catch (e) {
console.log(e instanceof TypeError); // true
console.log(e.message); // Cannot set property area of #<Object> which has only a getter
}ES modules and class bodies are always strict, so in modern code a write to a getter-only property usually throws. In older scripts it fails silently, which is harder to debug. Setter-only properties are rare and confusing, because reading one returns undefined. Use a method such as setLogLevel(level) instead.
Where to Store the Underlying Value
A setter that assigns to its own property name calls itself again:
const bad = {
set name(value) {
this.name = value; // calls this same setter again
}
};
try {
bad.name = "x";
} catch (e) {
console.log(e instanceof RangeError); // true: Maximum call stack size exceeded
}The real value needs to live under a different key. The three common choices are a differently named property, a closure variable, and a class private field.
A property named _name works, but it is only a convention. It is enumerable, it shows up in Object.keys and JSON.stringify, and any caller can write to it directly, which skips your validation.
A closure keeps the value truly private:
function createAccount(initial) {
let balance = initial;
return {
get balance() {
return balance;
},
set balance(value) {
if (typeof value !== "number" || !Number.isFinite(value) || value < 0) {
throw new RangeError(`Invalid balance: ${value}`);
}
balance = value;
}
};
}
const account = createAccount(100);
account.balance = 250;
console.log(account.balance); // 250
try {
account.balance = -5;
} catch (e) {
console.log(e.message); // "Invalid balance: -5"
}
console.log(Object.keys(account)); // ["balance"]In classes, private fields (#name) do the same job with less ceremony:
class Temperature {
#celsius = 0;
get celsius() {
return this.#celsius;
}
set celsius(value) {
if (value < -273.15) throw new RangeError("Below absolute zero");
this.#celsius = value;
}
get fahrenheit() {
return this.#celsius * 9 / 5 + 32;
}
}
const t = new Temperature();
t.celsius = 100;
console.log(t.fahrenheit); // 212
console.log(Object.keys(t)); // []
console.log(Object.getOwnPropertyNames(Temperature.prototype));
// ["constructor", "celsius", "fahrenheit"]Class accessors live on the prototype and are non-enumerable. Instances therefore have no own celsius property, and Object.keys(t) returns an empty array.
Defining Accessors with Object.defineProperty
You can also attach an accessor to an existing object. Omitted attributes default to false, the same as for data properties:
const rect = { width: 3, height: 4 };
Object.defineProperty(rect, "area", {
get() {
return this.width * this.height;
},
configurable: true
});
console.log(rect.area); // 12
rect.width = 10;
console.log(rect.area); // 40
console.log(Object.keys(rect)); // ["width", "height"]
console.log(JSON.stringify(rect)); // {"width":10,"height":4}Because enumerable defaulted to false, area is hidden from enumeration and serialization. That is often what you want for a derived value.
Lazy Getters That Replace Themselves
A getter runs on every read. If the computation is expensive and the result never changes, the getter can compute the value once and then replace itself with a data property:
const report = {
get data() {
console.log("computing...");
const value = Array.from({ length: 5 }, (_, i) => i * i);
Object.defineProperty(this, "data", {
value,
writable: false,
enumerable: true,
configurable: false
});
return value;
}
};
console.log(report.data); // logs "computing..." then [0, 1, 4, 9, 16]
console.log(report.data); // [0, 1, 4, 9, 16] with no recomputationThe conversion works only because literal accessors are configurable: true. If the getter is inherited from a prototype, this is the instance, so defineProperty creates an own data property on the instance and leaves the shared getter untouched. That is the usual way to cache a value per instance.
Accessors and Copying
Spread syntax and Object.assign read each source property and write the result. Reading an accessor calls its getter, so the copy receives a plain data property that holds a snapshot of the value:
const source = {
a: 1,
get double() {
return this.a * 2;
}
};
const spreadCopy = { ...source };
console.log(Object.getOwnPropertyDescriptor(spreadCopy, "double"));
// { value: 2, writable: true, enumerable: true, configurable: true }
const realCopy = Object.defineProperties({}, Object.getOwnPropertyDescriptors(source));
realCopy.a = 10;
console.log(realCopy.double); // 20
console.log(spreadCopy.double); // 2To keep accessors live in a copy, copy the descriptors instead of the values. Use Object.create(Object.getPrototypeOf(source), Object.getOwnPropertyDescriptors(source)) if the copy should also keep the same prototype. structuredClone also drops accessors: it calls getters and stores plain values.
Inherited Accessors and Shadowing
Assigning to a name that has an inherited data property creates an own property that shadows it. Inherited accessors do not work this way:
const shape = {
get description() {
return `${this.name} with ${this.sides} sides`;
}
};
const tri = Object.create(shape);
tri.name = "triangle";
tri.sides = 3;
console.log(tri.description); // "triangle with 3 sides"
try {
tri.description = "custom"; // inherited getter, no setter
} catch (e) {
console.log("TypeError in strict mode");
}
console.log(Object.hasOwn(tri, "description")); // false
console.log(tri.description); // "triangle with 3 sides"The assignment fails, and no own property appears. To override the accessor on one object, use Object.defineProperty(tri, "description", { value: "custom" }). That call defines a new property directly and skips the inherited accessor.
Common Errors and When to Use Accessors
| Mistake | Symptom | Fix |
|---|---|---|
| Setter writes to its own name | `RangeError: Maximum call stack size exceeded` | Store the value in a closure, a `#field`, or a different key |
| Arrow function as `get` in a descriptor | Getter returns `undefined` or throws | Use method syntax |
| Expecting spread to copy a getter | Copy shows a stale value | Copy descriptors with `getOwnPropertyDescriptors` |
| Slow or side-effecting getter | Debuggers and `console.log` trigger it unexpectedly | Make it a method, or cache it lazily |
| Writing to a getter-only property | Silent no-op or `TypeError` | Add a setter or expose a method |
Use an accessor when the value is cheap to compute, has no side effects, and behaves like data. Examples are a derived total, a unit conversion, or a validated field. If reading has a noticeable cost, can fail, or changes state, write a method. A method call signals to readers that work is happening.
Exercise
Write an object range with data properties min and max and an accessor span. Reading span returns max - min. Assigning span keeps min and sets max to min + value, and it throws a RangeError if the value is negative. What does range.span = 5; console.log(range.max) print when min is 2?
Show answer
const range = { min: 2, max: 4, get span() { return this.max - this.min; }, set span(v) { if (v < 0) throw new RangeError("negative span"); this.max = this.min + v; } }; After range.span = 5, range.max is 7, so the code prints 7.
Exercise
An object is created with const o = { get now() { return Date.now(); } }; and then copied with const c = { ...o };. Why does c.now return the same number on every read while o.now changes, and how would you make a copy whose now stays live?
Show answer
Spread reads o.now once, which calls the getter, and stores the result as a plain data property on c. The fix is to copy the descriptors so the getter itself is copied: const c = Object.defineProperties({}, Object.getOwnPropertyDescriptors(o));
Exercise
In a module, proto has a getter-only accessor id, and obj = Object.create(proto). What happens when you run obj.id = 5, and how can you give obj its own id of 5?
Show answer
Modules are strict, so the assignment throws a TypeError because the inherited accessor has no setter. No own property is created. Use Object.defineProperty(obj, "id", { value: 5, writable: true, enumerable: true, configurable: true }), which defines the own property directly and skips the inherited accessor.