Getters & Setters
A getter is a function that runs when a property is read, and a setter is a function that runs when a property is assigned. From the outside they look like ordinary properties, so code writes reading.fahrenheit, not reading.getFahrenheit(). Use them for a value that is worked out from other properties, or to check or tidy a value before it is stored. They have been part of JavaScript since ES5.
get and set in an object literal
Section titled “get and set in an object literal”get and set go in front of a method-like definition. Here fahrenheit is not stored at all, because both functions convert to and from the stored celsius property:
const reading = { celsius: 21, get fahrenheit() { return this.celsius * 9 / 5 + 32; }, set fahrenheit(value) { this.celsius = (value - 32) * 5 / 9; },};
console.log(reading.fahrenheit);reading.fahrenheit = 50;console.log(reading.celsius);console.log(reading.fahrenheit);This prints:
69.81050The getter is called with no brackets, and the setter is called by assigning with =, which passes the assigned value as the setter’s single argument. Calling either as a method, such as reading.fahrenheit(50), is an error, because reading reading.fahrenheit returns the number from the getter.
A getter on its own
Section titled “A getter on its own”A getter suits a value that should always be up to date with the data it comes from. Without a setter, the property is read-only:
const basket = { items: [], get total() { return this.items.reduce((sum, item) => sum + item.price, 0); },};
basket.items.push({ name: 'tea', price: 3.2 });basket.items.push({ name: 'oats', price: 1.8 });console.log(basket.total);
basket.total = 100;console.log(basket.total);This prints:
55The assignment to basket.total is ignored without any warning, because this example runs as a classic script in sloppy mode. In strict mode, which applies in ES modules and inside classes, the same assignment throws TypeError: Cannot set property total of #<Object> which has only a getter.
Checking a value in a setter
Section titled “Checking a value in a setter”A setter can reject a value or clean it up before storing it. The value needs to live in a second property, here _email, because a setter that assigned to this.email would call itself again without end:
const user = { _email: '', get email() { return this._email; }, set email(value) { if (!value.includes('@')) { throw new Error(`Not an email address: ${value}`); } this._email = value.trim().toLowerCase(); },};
user.email = ' Sam@Example.com ';console.log(user.email);
try { user.email = 'sam.example.com';} catch (err) { console.log(err.message);}console.log(user.email);This prints:
sam@example.comNot an email address: sam.example.comsam@example.comThe leading underscore is only a naming convention, so other code can still read and change user._email directly. Private Variables shows how to hide it.
Getters and setters in a class
Section titled “Getters and setters in a class”Classes use the same syntax, and a private field, written with #, gives the setter’s value somewhere to live that no outside code can reach:
class Thermostat { #target = 20;
get target() { return this.#target; }
set target(value) { this.#target = Math.min(Math.max(value, 5), 30); }}
const hall = new Thermostat();hall.target = 35;console.log(hall.target);hall.target = 18;console.log(hall.target);console.log(Object.keys(hall));This prints:
3018[]The setter keeps the target between 5 and 30. Object.keys(hall) is empty, because class getters and setters are defined on the class’s prototype rather than on each instance, and private fields are never listed.
Shorthand properties and methods
Section titled “Shorthand properties and methods”The same ES2015 object syntax that sits alongside getters and setters has two shortcuts. A property whose value comes from a variable of the same name needs only the name, and a method needs no function keyword:
const pages = 240;
const book = { title: 'A Field Guide to Mosses', pages, describe() { return `${this.title}, ${this.pages} pages`; },};
console.log(book.describe());This prints:
A Field Guide to Mosses, 240 pagesMethod Shorthand covers these in more detail, and Property Descriptors shows how to add a getter or setter to an object that already exists, with Object.defineProperty.
Steve Griffith covers this topic in his video ES5 Custom Object Methods, Getters, and Setters.