Getters (get) and setters (set) define accessor properties: reading the property calls a function, and assigning to it calls another. Callers keep plain obj.prop syntax while you get computed values, validation, lazy initialisation and encapsulation behind it. Use them for cheap, side-effect-free derivations; avoid hiding expensive work or surprising side effects behind what looks like a field access.
const user = {
first: 'Ada',
last: 'Lovelace',
get fullName() { return `${this.first} ${this.last}`; },
set fullName(value) {
[this.first, this.last] = value.split(' ');
},
};
user.fullName; // 'Ada Lovelace'
user.fullName = 'Grace Hopper';
user.first; // 'Grace'
In classes, accessors go on the prototype (shared, non-enumerable) and pair well with #private fields:
class Temperature {
#celsius = 0;
get celsius() { return this.#celsius; }
set celsius(v) {
if (typeof v !== 'number' || Number.isNaN(v)) throw new TypeError('number expected');
this.#celsius = v;
}
get fahrenheit() { return this.#celsius * 9 / 5 + 32; } // read-only derived value
}
const t = new Temperature();
t.celsius = 25;
t.fahrenheit; // 77
t.fahrenheit = 0; // ignored in sloppy mode, TypeError in strict mode (no setter)
You can also add accessors to existing objects with Object.defineProperty(obj, 'x', { get, set }).
fullName, area, isEmpty).set email(v) { this.#email = v.trim().toLowerCase(); }).const config = {
get parsed() {
const value = JSON.parse(hugeString);
Object.defineProperty(this, 'parsed', { value }); // later reads skip the getter
return value;
},
};
obj.size to obj.getSize().set name(v) { this.name = v; } calls itself. Store the value in a separate (ideally private) field.Object.assign and JSON.stringify call the getter and copy the value. Class getters live on the prototype and aren't copied at all.undefined.(...) until you click to invoke a getter, because evaluating it might have side effects.#private fields for validation and read-only views.Spotted a mistake or a rights concern? Report an issue