Getters And Setters used in JavaScript Objects....How?

Published May 14, 2018Last updated May 25, 2018

A common object paradigm is to include getter and setter method as attributes. Getter and Setter methods get and set the properties of an object.


  1. You can check if new data is valid before setting a property
  2. You can perform an action on the data which you are getting or setting on a property.
  3. You can control which properties can be stored and retrieved.

An Example showing how Setter is used is shown below:

let person = { _name: 'Johnson Ogwuru', _age: 137, set age(newage){ if(typeof newage === 'number'){ this._age = newage; console.log('valid input') } else{ console.log ('Invalid input'); } } };

We prepended the property names with underscores _. Developers use an underscore to indicate a property or value should not be modified directly by other codes. The setter here makes sure only valid values are added to a particular property, validity here is for the value to be a number, but what happen when we try to add a string to this property? Lets see what adding this line below our code would do;

person.age = 'Thirty-nine';//returns invalid input console.log(person._age);

invalid input

From the above we see that on running the Application, we got logged in the console 'invalid value' and we also noticed the value of the age property wasn't changed. But how about we try modifying the age parameter now with the right value. lets see what happens, change the string in the previous code to any number of your choice;

person.age = 'Thirty-nine';//returns invalid input console.log(person._age);

valid input

From the above image, our value was accepted as valid and also the value of the age property was modified successfully. That's it for Setters.

Getters are used to get the property value inside of an object. Adding a getter method to our previous example, we would have something like;

let person = { _name: 'Johnson Ogwuru', _age: 137, set age(newage){ if(typeof newage === 'number'){ this._age = newage; console.log('valid input') } else{ return 'Invalid input'; } }, get age(){ console.log(`${this._name} is ${this._age} old`); return this._age } }; person.age = 'Thirty-nine'; person.age = 39; console.log(person.age);

Running the above code we have;

Getter image

In Summary:
Getter and Setter methods allow you to process data before accessing or setting property values.

Let's see how we can use setter and getter methods in Es6 classes..... in my next post. LOL is where software developers stay in the loop and avoid career stagnation. Signing up (for free!) is the first step.

Discover and read more posts from Ogwuru Johnson
get started