ES6: getters and setters

Don’t let getters and setters throw you. They are syntactic shortcuts. They do one thing: allow a slightly more convenient way to get or set the value of a property in a class/object. That’s it. They are not required. You could never use them and you would be able to write perfectly fine JS. But since they exist and a lot of people do use them, you will most likely run into them down the road and thus need to know about them.

Two of the most common methods people write when using classes/objects are “getters” to retrieve the value of a property and “setters” to set/change the value of a property. So you will often see a bunch of methods with names like getTemp() and setTemp() in order to get the value of the property temp and set the value of temp. I guess people thought this was ugly or maybe they thought typing out getTemp took too much time :slight_smile: Regardless, using getters and setters in JS allows you to forgo the traditional function-like syntax and instead use the fancy dot syntax to get/set the property value.

Traditional:

getTemp() {
  return this.temp;
}

To get the value of temp you would need to call this method as you normally would any other method (assume myTemp is an instance of the class):

console.log(`The current temp is ${myTemp.getTemp()}`);

Do you see how ugly that is, having to use parens to call a method to get the value of temp!!! Outrageous.

Instead, if we define a getter for temp we can do away with all of this nonsense.

get temp() {
   return this.temp;
}

Now we can write our console.log the way Nature intended it to be:

console.log(`The current temp is ${myTemp.temp}`);

Can you see how much better this is? I mean, I don’t know how I lived without this for so many years.

And setters are even better, because we can use the equals sign!

Traditional:

setTemp(t) {
  this.temp = t;
}

To set the temp you would have to do:

myTemp.setTemp(50);

My fingers are aching after having to type so many characters. Instead, if we define a setter:

set temp(t) {
  this.temp = t;
}

Now I can avoid carpal tunnel by doing:

myTemp.temp = 50;

OK, I am being very silly here. I’m just trying to make the point that there is no magic with setters/getters, they just allow you to do some very basic things that everybody needs to do with a slightly different syntax. Whether you think that syntax is actually better is a personal opinion (there are those who think that the getter/setter syntax is actually more confusing).

5 Likes