

0 / 2 embers
0 / 3000 xp
click for more info
Complete a lesson to start your streak
click for more info
Difficulty: 6
click for more info
Not enough gems
Cost: 6 gems
1: Classes
incomplete
2: Private Properties
incomplete
3: Static Methods
incomplete
4: Getters and Setters
incomplete
5: Inheritance
incomplete
6: Super
incomplete
This lesson's interactive features are locked, please to keep using them
In JavaScript classes, getters and setters let us define special methods for getting and setting the values of properties. They look like regular methods but are accessed like properties. Here's an example using the get keyword:
class User {
constructor(name, age) {
this._name = name;
this.age = age;
}
get name() {
return this._name.toUpperCase();
}
}
const lane = new User("Lane", 30);
console.log(lane.name); // LANE
Notice that we've renamed this.name to this._name in our constructor to avoid a name collision with the getter itself.
A setter lets us control what happens when a property is changed. For example, we could validate a user's age to make sure it's not negative:
class User {
constructor(name, age) {
this.name = name;
this._age = age;
}
get age() {
return this._age;
}
set age(value) {
if (value < 0) {
throw new Error("Age can't be negative.");
}
this._age = value;
}
}
const lane = new User("Lane", 29);
lane.age = -5; // "Age can't be negative."
console.log(lane.age); // 29
Personally... I hate this. When I get or set a value in property field, I expect that I'm dealing with a raw value, not calling a custom function! There are certain patterns that make heavy use of this feature (e.g. reactive state in certain front-end frameworks), but my advice is to only use it when you truly need it.
Textio's Contact class currently accepts invalid phoneNumbers and doesn't format them well when displayed. Fix this by implementing getters and setters.
Strings have a .slice() method that should be useful.