Sub topic 2
Your First Getter and Setter
This chapter assumes you know how to create objects and read their properties, how this works inside a method, and the difference between data properties and accessor properties from the previous chapter. Here you will write accessors directly in an object literal, the shortest way to create them.
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 that property. In an object literal, you put the get or set keyword in front of a method-style 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); // falseThe object holds one piece of real state, celsius. The fahrenheit property stores nothing. Each read calculates the value, and each write converts the input and stores the result in celsius. The two values cannot drift apart because only one of them exists.
The descriptor check at the end confirms what the previous chapter described. fahrenheit is an accessor property, so its descriptor has get and set functions and no value key.
What Happens on Read and Write
Calling code never uses parentheses. temperature.fahrenheit looks like plain property access, and JavaScript calls the getter for you. Assignment works the same way: the right-hand side becomes the setter's single argument.
Inside both functions, this is the object the property was accessed on. That is why this.celsius refers to the right object.
Rules You Need to Know
| Rule | Detail |
|---|---|
| Getter parameters | A getter takes no parameters. |
| Setter parameters | A setter takes exactly one parameter. Zero or two is a `SyntaxError`. |
| Setter return value | Ignored. An assignment expression evaluates to the right-hand side, not to what the setter returns. |
| Getter only | Reading works. Assignment is silently ignored in sloppy mode and throws a `TypeError` in strict mode. |
| Setter only | Assignment works. Reading returns `undefined`. |
| Same name as a data property | Not allowed together. The later definition in the literal replaces the earlier one. |
Getters and setters can also use computed names, such as get [key]() { ... }, when the property name comes from a variable.
Common Mistakes
- Calling the getter like a method.
temperature.fahrenheit()throwsTypeError: temperature.fahrenheit is not a function, because the read returns a number. - Using an arrow function. Accessor syntax always creates normal functions. If you build a property some other way and wrap the logic in an arrow function,
thiswill not be the object. - Storing the value under the accessor's own name. Writing
this.fahrenheit = valueinsideset fahrenheitcalls the setter again and recurses forever. Store the state under a different name. A later chapter covers this pitfall in detail. - Slow or side-effecting getters. Callers expect property reads to be cheap and safe to repeat. If a read does heavy work or changes state, a regular method is clearer.
Exercises
Exercise
Add a read-only fullName getter to const person = { first: 'Ada', last: 'Lovelace' } that returns the first and last names separated by a space. What does person.fullName log after person.first = 'Augusta'?
Show answer
Define get fullName() { return ${this.first} ${this.last}; } inside the literal. The getter recalculates the value on every read, so it logs 'Augusta Lovelace'.
Exercise
In strict mode, what happens when you run temperature.fahrenheit = 50 if the object defines only get fahrenheit and no setter?
Show answer
The assignment throws a TypeError, because the accessor property has no setter. In sloppy mode the assignment would be silently ignored and celsius would stay the same.
Exercise
Why does const result = (temperature.fahrenheit = 212); set result to 212 even if the setter were changed to return 'ignored';?
Show answer
An assignment expression evaluates to its right-hand operand. JavaScript throws away whatever the setter returns.