DEV Community

Srijan
Srijan

Posted on • Originally published at hackinbits.com

Getters and Setters in Javascript

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',
}
Enter fullscreen mode Exit fullscreen mode

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'
Enter fullscreen mode Exit fullscreen mode

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}`;
  }
}  
Enter fullscreen mode Exit fullscreen mode

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'
Enter fullscreen mode Exit fullscreen mode

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'
}
Enter fullscreen mode Exit fullscreen mode

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;
  }
};
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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

Top comments (0)