Full answer
In an object literal or a class, get name() {} defines a property whose value is computed on each read, and set name(value) {} runs on assignment. To the caller they look like ordinary properties: account.balance, account.balance = 5.
The common reasons to use them are:
- Computed values:
get fullName()returns first and last name joined, with no stored copy to get out of date. - Validation: a setter can reject a negative age or trim text before it is stored.
- Encapsulation: a private field
#balanceholds the data, a getter exposes it read-only, and no setter means no outside writes. Assigning to a getter-only property is ignored in sloppy mode and throws aTypeErrorin strict mode, which includes class bodies and modules. - Compatibility: a plain field can later become a getter and setter pair without changing the code that uses it.
Details worth knowing: a class getter lives on the prototype, so it is not an own property and is skipped by Object.keys, spread, and JSON.stringify. A setter without a getter makes the property read as undefined. Static getters belong to the class itself. A getter is called on every read, so an expensive one should cache its result. A getter that changes state makes debugging harder, because even logging the object runs it.
A common mistake is a setter that assigns to its own property name, set age(v) { this.age = v }, which calls itself forever and ends in a RangeError. Store the value in a differently named or private field.
'use strict';
class Temperature {
#celsius = 0;
constructor(celsius) {
this.celsius = celsius; // goes through the setter
}
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;
}
get fahrenheit() {
return this.#celsius * 9 / 5 + 32;
}
static get freezingPoint() {
return 0;
}
}
const t = new Temperature(25);
console.log(t.celsius, t.fahrenheit, Temperature.freezingPoint);
t.celsius = 100;
console.log(t.fahrenheit);
for (const bad of ['hot', -300]) {
try {
t.celsius = bad;
} catch (error) {
console.log(error.name, '-', error.message);
}
}
try {
t.fahrenheit = 50; // no setter: class code is strict
} catch (error) {
console.log('getter only:', error.name);
}
console.log(Object.keys(t), JSON.stringify(t), Object.hasOwn(t, 'fahrenheit'));
class Broken {
set value(v) {
this.value = v; // calls the setter again
}
}
try {
new Broken().value = 1;
} catch (error) {
console.log('recursive setter:', error.name);
}
const cart = {
items: [{ price: 40, qty: 2 }, { price: 15, qty: 1 }],
get total() {
return this.items.reduce((sum, item) => sum + item.price * item.qty, 0);
},
};
console.log(cart.total);
cart.items.push({ price: 5, qty: 4 });
console.log(cart.total);Run with Node.js v24.22.1 as js-57.js; two runs gave identical output. Output: 25 77 0 212 TypeError - celsius must be a number RangeError - below absolute zero getter only: TypeError [] {} false recursive setter: RangeError 95 115
Key points
- get runs on read, set runs on write; the call syntax is a plain property.
- Use for computed values, validation, and read-only views of private fields.
- Class accessors live on the prototype, so JSON.stringify and spread skip them.
- Assigning to a getter-only property throws in strict mode.
- A setter must not assign to the same property name, or it recurses.
Common mistakes
- Writing a setter that assigns to the same property name and recurses until a RangeError.
- Putting slow work or side effects in a getter.
- Expecting JSON.stringify or spread to include class getters.
- Making every field a getter and setter pair with no logic, which adds noise.
Follow-ups
- How do you define a getter on an existing object with Object.defineProperty?
- How do accessors interact with inheritance and super?
- How would you cache an expensive getter result and invalidate it?
Tips
- Lead with two uses: computed values and validation.
- Show a private field behind a getter; it is the modern encapsulation answer.
- State that getters should stay cheap and predictable.