Hint
Accessor properties β run a function on read (get) or write (set)
Getters and setters are special methods that execute code when a property is read or written β they look like properties but behave like functions.
const user = {
firstName: 'John',
lastName: 'Doe',
get fullName() {
return `${this.firstName} ${this.lastName}`; // computed on read
},
set fullName(val) {
[this.firstName, this.lastName] = val.split(' '); // validated on write
}
};
console.log(user.fullName); // 'John Doe' β runs getter
user.fullName = 'Jane Smith'; // runs setter
console.log(user.firstName); // 'Jane'
// In a class
class Temperature {
constructor(celsius) { this._c = celsius; }
get fahrenheit() { return this._c * 9/5 + 32; }
set fahrenheit(f) { this._c = (f - 32) * 5/9; }
}
const t = new Temperature(0);
console.log(t.fahrenheit); // 32
t.fahrenheit = 212;
console.log(t._c); // 100