Press "Enter" to skip to content

Simple guide to getters and setters in JavaScript

In javascript, Getter and setters are methods available that help users to retrieve and set the value of the property. If you use laravel, you must have seen some code in your Eloquent model like this.

It is providing us with a full name attribute that does not even exists. It combines first name, middle name and last name, removes the empty ones and joins it with space. So when required, you can simply call $user->full_name. Similarly, we can also define setAgeAttribute(); or something like that in an eloquent model.  For example, setAgeAttribute that calculates age based upon birthday.

This idea is very much inspired by javascript.

In javascript, using getters and setters we can control how we mutate the data of an object. Both methods are called Mutator method. Using this we can validate data so the data is valid therefore next action of the class can be measured. Not just that, we can keep our applicable simple with its help. It is not compulsory in javascript. It is not even a must do in javascript.

From mozilla.org

getter is a method that gets the value of a specific property. A setter is a method that sets the value of a specific property. You can define getters and setters on any predefined core object or user-defined object that supports the addition of new properties. The syntax for defining getters and setters uses the object literal syntax.

Take a look at this example.

Notice that, a ‘code’ is an object that contains a repo of letters with mutators.

To retrieve all letters, we can simply do

Or to set letters, we can simply do

Not just that,

We can have additional getter methods that just return some specific values like:

Most of the new frameworks in javascript been built using this idea. For example, vue.

Everything is awesome.