DEV Community

loading...

Getters and Setters in Javascript

srijan82239366 profile image Srijan Originally published at hackinbits.com ・2 min read

This article is first published on hackinbits.com.


Alt Text

In Javascript, getters and setters are used for defining Object Accessors(Computed Properties). Accessor uses a function to get or set the value of an Object. Accessors are useful when some operations are needed to be performed automatically before setting or retrieving an object’s value, like reformating strings, accessing private properties, triggering events, etc.

Getter

To keep it simple, let’s consider a common scenario, where we wanted to get a user’s full name from the below object.

let user = {
  firstName: 'John',
  lastName: 'Doe',
}

We can achieve this by concatenating the firstName and lastName properties of the user object.

let fullName = `${user.firstName} ${user.lastName}`;
console.log(fullName);
// 'John Doe'

The above code works fine, but there is a better way to achieve the same. Let’s look at the example below:

let user = {
  firstName: 'John',
  lastName: 'Doe',
  get fullName () {
 return `${user.firstName} ${user.lastName}`;
  }
}  

We defined a getter named fullName in the above object to return the complete name of the user. Now full name can be accessed like any other properties of the object.

console.log(user.fullName)
// 'John Doe'

So, in the above example, we achieved our requirement of concatenating two properties of an object before retrieving the required value i.e. fullName.

Setter

The setter is used to do some required operations before setting the value of an object.

For example, you have an input field for the user’s name. But, the object in which the value needs to be stored is having firstName and lastName.

let user = {
  firstName: 'John',
  lastName: 'Doe'
}

To achieve this, we will use setter.

let user = {
  firstName: 'John',
  lastName: 'Doe',
  set fullName (name) {
    let [fName, lName] = name.split(' ');
    this.firstName= fName; 
    this.lastName = lName;
  }
};

Now to set the value of firstName and lastName, we can simply assign fullName like an object property and our setter function will handle the rest.

user.fullName = 'Peter Parker'

console.log(user.firstName);
//Peter
console.log(user.lastName);
//Parker

In the next article, we will learn how to define setter and getters for already defined objects using Object.defineProperty(). Have a nice day!

Discussion (0)

pic
Editor guide