Sub topic 2
Your First Getter and Setter
This chapter assumes you know how to create objects and read and write their properties, how this works inside regular functions and methods, and roughly how prototypes link objects together. The previous chapter covered the difference between data properties and accessor properties. Here you will write accessors directly in object literals. That syntax is the shortest way to create them, and it shows most of the behavior you will meet again in classes.
The syntax
A getter is a function that runs when code reads a property. A setter is a function that runs when code assigns to a property. In an object literal, you write them with the get and set keywords in front of an ordinary method definition:
const temperature = {
celsius: 20,
get fahrenheit() {
return this.celsius * 9 / 5 + 32;
},
set fahrenheit(value) {
this.celsius = (value - 32) * 5 / 9;
}
};
temperature.fahrenheit = 212;
console.log(temperature.celsius); // 100
console.log(temperature.fahrenheit); // 212
const desc = Object.getOwnPropertyDescriptor(temperature, 'fahrenheit');
console.log(typeof desc.get, typeof desc.set); // 'function' 'function'
console.log('value' in desc); // falseLook at how the code uses it. Nobody calls temperature.fahrenheit(). Code reads and assigns fahrenheit the same way it would a plain field, and the engine routes those operations to your functions. The get fahrenheit and set fahrenheit definitions do not create two properties. They combine into a single accessor property whose descriptor has get and set slots and no value slot.
Notice also that fahrenheit stores nothing itself. The only stored number is celsius. Fahrenheit is derived from it on every read, and a write to fahrenheit becomes a write to celsius. Because there is only one source of truth, the two values cannot drift out of sync.
Rules the syntax enforces
The parser checks accessor definitions, and some mistakes are syntax errors before any code runs:
| Rule | Example that fails | Error |
|---|---|---|
| A getter takes no parameters | `get x(a) {}` | SyntaxError |
| A setter takes exactly one parameter | `set x() {}` or `set x(a, b) {}` | SyntaxError |
| A setter cannot use a rest parameter | `set x(...a) {}` | SyntaxError |
A setter may use a default value or destructuring for its single parameter, so set point({ x, y }) {} is legal. Whatever a setter returns is thrown away. The assignment expression obj.x = 5 always evaluates to 5, the right-hand side, and not to the setter's return value.
How `this` gets bound
Inside a getter or setter, this is the receiver, meaning the object the property was accessed through. It is not necessarily the object where the accessor was defined. This matters as soon as prototypes are involved:
const base = {
_name: 'base',
get name() {
return this._name.toUpperCase();
},
set name(value) {
this._name = value;
}
};
const child = Object.create(base);
child.name = 'kid';
console.log(child.name); // 'KID'
console.log(base.name); // 'BASE'
console.log(Object.hasOwn(child, 'name')); // false
console.log(Object.hasOwn(child, '_name')); // trueTwo things happen here that do not happen with data properties. First, child.name = 'kid' does not create an own name property on child. The engine walks the prototype chain, finds an accessor on base, and calls its setter. With an inherited data property, assignment would instead shadow it with a new own property. Second, the setter runs with this === child, so _name lands on child while base keeps its own _name.
The leading underscore on _name is only a naming convention. It means "please don't touch," and nothing enforces it. Later chapters replace it with real private fields.
Getter-only and setter-only properties
You don't have to define both halves. A property with only a getter is effectively read-only. What happens when someone assigns to it depends on strict mode:
'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 (err) {
console.log(err instanceof TypeError); // true
}
circle.radius = 1;
console.log(circle.area.toFixed(2)); // '3.14'In sloppy mode, the same assignment does nothing and reports nothing. Code inside ES modules and class bodies is always strict, so you will usually get the TypeError. Older scripts may still fail silently.
A property with only a setter is less common. Reading it returns undefined:
const logger = {
entries: [],
set message(text) {
this.entries.push(`${new Date().toISOString()} ${text}`);
}
};
logger.message = 'started';
logger.message = 'finished';
console.log(logger.entries.length); // 2
console.log(logger.message); // undefinedThis works, but it surprises readers, because x = v followed by reading x normally gives back v. A method like logger.log('started') is usually clearer.
Computed accessor names
Accessor names can be computed, just like method names. Put the expression in square brackets:
const prefix = 'full';
const person = {
first: 'Ada',
last: 'Lovelace',
get [`${prefix}Name`]() {
return `${this.first} ${this.last}`;
},
set [`${prefix}Name`](value) {
[this.first, this.last] = value.split(' ');
}
};
person.fullName = 'Grace Hopper';
console.log(person.first); // 'Grace'
console.log(person.fullName); // 'Grace Hopper'Symbols work too, as in get [Symbol.toStringTag]() { return 'Person'; }, which changes what Object.prototype.toString.call(person) reports.
Duplicate names: the last definition wins
An object literal may mention the same key more than once, and later definitions replace earlier ones. A getter and a setter with the same name merge into one accessor. A data property and an accessor with the same name do not merge:
const a = { x: 1, get x() { return 2; } };
console.log(a.x); // 2, and x is now a getter-only accessor
const b = { get x() { return 2; }, x: 1 };
console.log(b.x); // 1, and x is now a plain data property
const d = Object.getOwnPropertyDescriptor(a, 'x');
console.log(d.set); // undefinedIn object a, the data property was replaced, so in strict mode a.x = 5 now throws. Linters flag duplicate keys for this reason (ESLint's no-dupe-keys).
Accessors are invoked when objects are copied
Spread syntax, Object.assign, destructuring, and JSON.stringify all read properties the ordinary way. That means they call your getters and use the results. They do not copy the accessor itself:
const temp = {
celsius: 100,
get fahrenheit() {
return this.celsius * 9 / 5 + 32;
}
};
const copy = { ...temp };
console.log(Object.getOwnPropertyDescriptor(copy, 'fahrenheit'));
// { value: 212, writable: true, enumerable: true, configurable: true }
copy.celsius = 0;
console.log(copy.fahrenheit); // 212, a frozen snapshot rather than a live value
console.log(JSON.stringify(temp)); // '{"celsius":100,"fahrenheit":212}'Object-literal accessors are own properties and they are enumerable, so they show up in Object.keys, for...in, spreads, and JSON. This is different from class accessors, which live on the prototype. The pitfalls chapter covers what that difference means for serialization.
A lazy getter that replaces itself
Sometimes computing a value is expensive and you only want to do it on first use. Object-literal accessors are configurable, so a getter can delete itself and leave a plain data property behind:
const config = {
get settings() {
console.log('loading settings');
const value = { port: 8080, debug: false };
delete this.settings; // remove the accessor
this.settings = value; // create an ordinary data property
return value;
}
};
console.log(config.settings.port); // 'loading settings', then 8080
console.log(config.settings.port); // 8080, with no second load
console.log('get' in Object.getOwnPropertyDescriptor(config, 'settings')); // falseThe order matters. If you skip the delete, the assignment this.settings = value hits the getter-only accessor. That throws in strict mode, and in sloppy mode the cache is silently never stored. This trick also only works when the accessor is an own property of the receiver. If the getter lived on a prototype, delete this.settings would remove nothing from the receiver, and the assignment would still find the inherited getter-only accessor and fail.
Common errors at a glance
| Symptom | Likely cause |
|---|---|
| `RangeError: Maximum call stack size exceeded` | The setter assigns to its own name (`this.x = v` inside `set x`) |
| Reading returns `undefined` | Only a setter is defined, or the getter forgot to `return` |
| Assignment silently ignored | A getter-only property in sloppy-mode code |
| Copied object no longer updates | Spread or `Object.assign` turned the accessor into a data snapshot |
| Getter reads the wrong object's data | `this` is the receiver, for example a child created with `Object.create` |
Exercise
Write an object rect with data properties width and height and an accessor size. Reading rect.size returns a string like "3x4". Assigning rect.size = "10x2" sets width to 10 and height to 2 as numbers. What does ({ ...rect }).size return after the assignment, and is it still an accessor?
Show answer
One solution: const rect = { width: 3, height: 4, get size() { return ${this.width}x${this.height}; }, set size(v) { const [w, h] = v.split('x').map(Number); this.width = w; this.height = h; } };. After rect.size = "10x2", the spread copy's size is the string "10x2", but it is a plain data property. The spread called the getter once and copied the result, so changing the copy's width afterwards does not change its size.
Exercise
Given const proto = { get id() { return 1; } }; const obj = Object.create(proto);, what happens when strict-mode code runs obj.id = 2, and why doesn't it simply create an own property on obj?
Show answer
It throws a TypeError. Assignment looks up id along the prototype chain and finds an accessor on proto with no setter, so the assignment fails instead of shadowing the property. Only inherited data properties (and only writable ones) get shadowed by assignment. To give obj its own id, you would need Object.defineProperty, which the next chapter covers.
Exercise
In the object literal { get v() { return 1; }, set v(x) {}, v: 3 }, what kind of property is v, and what is its value?
Show answer
It is a plain data property with value 3. The getter and setter first merge into one accessor, and then the later v: 3 definition replaces that accessor entirely.