Getters and Setters
A getter is a function that runs when a property is read, and a setter is a function that runs when it is assigned. Together they let a property look like plain data while executing code behind the scenes.
Detailed Explanation
Say you are modelling a User with firstName and lastName, and the interface wants a full name. You could add a getFullName() method, but every caller then has to remember the parentheses, and the day you change how the name is derived, every call site is affected. A getter lets you expose user.fullName as a property that is computed on each read.
The syntax is the get and set keywords, in object literals and in class bodies. A getter takes no parameters and returns a value. A setter takes exactly one parameter and its return value is discarded. Under the hood these are accessor properties: instead of a value and a writable flag, the property holds get and set functions. Object.defineProperty can create the same thing at runtime.
The practical reasons to reach for them are few but real. Derived values, like an area computed from width and height, stay consistent because there is nothing to keep in sync. Validation on write means an invalid value never gets stored, so user.email = "nope" can throw at the moment of the mistake rather than three layers away. Lazy computation lets an expensive value be produced on first read. And a getter is the only way to turn what was already a data property into computed behaviour without changing any caller.
Inside a class, get and set create accessors on the prototype, shared by every instance and non-enumerable like other class methods. In an object literal they sit on that object as own properties. A getter with no matching setter makes the property effectively read-only: assignment is ignored in sloppy mode and throws TypeError in strict mode, which includes all module and class code.
The usual backing pattern is a private field for real storage and an accessor pair for the public surface. That is the JavaScript version of encapsulation: #celsius holds the number, get fahrenheit() and set fahrenheit(v) present a second unit without duplicating state.
The costs deserve honesty. A getter looks free and is not: it is a function call on every read, and engines cannot always inline it. Nobody expects order.total to hit the network or mutate anything, so a getter that is slow or has side effects is a trap for the next reader. Getters are not cached, so reading one in a loop recomputes it every iteration; hoist it into a local variable instead. Accessors also make debugging harder, because a plain-looking assignment can now throw, and console.log of the object may not show what you expect.
The rule of thumb: use an accessor when the property is conceptually data and the work is cheap and pure. Use an explicit method when the operation is expensive, asynchronous, or changes state. If the name reads like a noun, an accessor fits; if it reads like a verb, write a method.
Code Examples
class Temperature {
#celsius = 0; // real storage, private to the class
get celsius() {
return this.#celsius;
}
set celsius(value) {
if (typeof value !== "number" || Number.isNaN(value)) {
throw new TypeError("celsius must be a number");
}
if (value < -273.15) {
throw new RangeError("below absolute zero");
}
this.#celsius = value;
}
// A second view of the same single piece of state.
get fahrenheit() {
return this.#celsius * 1.8 + 32;
}
set fahrenheit(value) {
this.celsius = (value - 32) / 1.8; // reuse the validating setter
}
}
const t = new Temperature();
t.fahrenheit = 212;
console.log(t.celsius); // => 100
// Invalid data is rejected at the point of the mistake.
try {
t.celsius = -300;
} catch (err) {
console.log(err.constructor.name); // => RangeError
}
// Accessors live on the prototype and are not own properties.
console.log(Object.keys(t)); // => []const report = {
rows: [{ amount: 20 }, { amount: 22 }],
// Getter with no setter: read-only from the outside.
get total() {
return this.rows.reduce((sum, r) => sum + r.amount, 0);
},
};
console.log(report.total); // => 42
report.rows.push({ amount: 8 });
console.log(report.total); // => 50 (recomputed, never stale)
// Not cached: this recomputes the reduce on every iteration.
for (let i = 0; i < 3; i++) console.log(report.total);
// Hoist it when the value cannot change inside the loop.
const total = report.total;
// Lazy, computed once, then replaced by a plain value.
const settings = {
get parsed() {
const value = JSON.parse('{"theme":"dark"}'); // pretend this is expensive
Object.defineProperty(this, "parsed", { value, configurable: true });
return value;
},
};
console.log(settings.parsed.theme); // => dark (getter runs once)Common Gotchas
A setter that assigns to its own property recurses forever
writing `set name(value) { this.name = value; }` calls the setter again and ends in `RangeError: Maximum call stack size exceeded`. Store the value somewhere else: a private field such as `#name`, or a differently named backing property.
Assignment to a getter-only property is silent or fatal depending on mode
in sloppy mode the write is discarded and the old value remains, which looks like the assignment worked until the next read. In strict mode, and therefore in every module and class body, it throws `TypeError`.
Getters are recomputed on every read
there is no memoisation. Reading `order.total` a thousand times runs the computation a thousand times. Cache in a local variable, or overwrite the accessor with a data property once the value is settled.
Spread and JSON flatten getters
`{ ...user }` and `JSON.stringify(user)` call each getter once and store the result, so the copy holds a frozen snapshot rather than live behaviour. Class accessors live on the prototype, so they are not copied at all.