What getters and setters are
A getter lets other code read a private field. A setter lets other code change it, but only to values the class accepts. In JavaScript they are written with the keywords get and set in front of a method name.
class Dog {
#age;
constructor(age) {
this.#age = age;
}
get age() {
return this.#age;
}
set age(value) {
if (value >= 0) {
this.#age = value;
}
}
}
The private field is #age. The getter and the setter are both named age, without the #. Code outside the class never sees the field. It sees what looks like a plain property called age.
How they are used
A getter runs when the property is read, and a setter runs when it is assigned. There are no parentheses in either case:
let rex = new Dog(3);
console.log("Rex is " + rex.age);
rex.age = -5;
console.log("Rex is still " + rex.age);
rex.age = 4;
console.log("Rex is " + rex.age);
Rex is 3
Rex is still 3
Rex is 4
rex.age on the right runs get age(). The line rex.age = 4 runs set age(value) with value equal to 4. The assignment rex.age = -5 also runs the setter, but the if fails, so #age keeps its old value and the program prints "Rex is still 3".
Why not a plain field?
With a plain this.age, any code could assign -5 and nothing would check it. With a setter, the rule "an age is never negative" lives inside the class, in one place. The code that uses rex.age looks the same either way, so a class can start with a plain property and later add a rule without changing its users.
The exercise, step by step
- Write the getter. Below the constructor add
get age()with its braces. It returnsthis.#age. - Open the setter. Below the getter add
set age(value), again with braces. A setter takes exactly one parameter, the assigned value. - Add the rule. Inside the setter, an
ifonvalue >= 0storesvalueinthis.#age. For a negative value nothing happens.
The solution, with the code that prints the expected output:
class Dog {
#age;
constructor(age) {
this.#age = age;
}
get age() {
return this.#age;
}
set age(value) {
if (value >= 0) {
this.#age = value;
}
}
}
let rex = new Dog(3);
console.log("Rex is " + rex.age);
rex.age = -5;
console.log("Rex is still " + rex.age);
rex.age = 4;
console.log("Rex is " + rex.age);
Traps
- The accessor and the field need different names. The getter is
ageand the field is#age. If the getter readsthis.ageit calls itself, and the program stops withRangeError: Maximum call stack size exceeded. - A getter without a setter is read-only. With only
get age(), the assignmentc.age = 9does nothing in ordinary top-level code, andc.agestill returns the old value. Inside a class body or a strict-mode function it throwsTypeError: Cannot set property age of #<Cat> which has only a getter. - The setter's rejection is silent. Assigning -5 gives no error. If callers should be told, throw an error in the setter instead of skipping the assignment.
- Accessors are not properties of the object itself. They live on the class, so
Object.keys(rex)andJSON.stringify(rex)give an empty list and{}, and the private field does not show up either.
Key takeaways
get name()runs whenobj.nameis read.set name(value)runs whenobj.name = valueis assigned.- Keep the data in a
#field with a different name from the accessor. - Put the validation in the setter, so the rule exists in one place.
- Leave out the setter to make a value readable but not changeable.
