Getters And Setters used in JavaScript Objects....How?
Tags: javascript, tutorial, programming
Published: 2018-05-13 00:12:48

---
title: Getters And Setters used in JavaScript Objects....How?
published: true
description: we would be looking at a practical way of using Getters and setters in JavaScript with examples.
tags: javascript,tutorial,programming
---

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.

**Advantages:**

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](https://thepracticaldev.s3.amazonaws.com/i/jaa70xaes00w4bih1u0r.PNG)

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](https://thepracticaldev.s3.amazonaws.com/i/xzqnw45c5m1mscly5tdr.PNG)

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](https://thepracticaldev.s3.amazonaws.com/i/hqqnncsuywep04ugp7wu.PNG)

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