Easy JavaScript Part 8: What are getters and setters?

In JavaScript, you may have heard of getters and setters. Let’s take a look at what these things are.

First, a setter is used to set the value of a property. A setter gets called each time the value of the property is changed. In other words, it executes a function for each time a property used inside the setter function is changed. Take a look at the following code:

Above, you are adding a setter to an existing object, and you’ll get 9 as your output.

JavaScript getter

Using a JavaScript getter, you can call a function each time you do a property reading. So, if you want to call a function, JavaScript will use a getter each time an object is looked up. Consider the following code:

In the above code, your output will be the computed value of the property num. Mainly, you’re going to use getters to read the value of a property that returns a dynamically computed value. If you need to read the value of a property on the following criteria:

The property will return dynamic computed value

The property’s internal value should not be reflected without calling a method explicitly

To achieve these two requirements, you should use a getter. Consider the code below:

As you can see above, you’re adding a getter to an existing object, and your output will be 2.

Conclusion

Having a good understanding of getters and setters is necessary to work with objects in JavaScript. Using a setter, you can call a function each time the value of a property is changed, and using a getter, you can return the computed value of a property. And that’s it!