An Introduction to JavaScript Getters and Setters 👓
Tags: javascript
Published: 2020-07-18 05:39:34

Suppose we have a JavaScript Object, as we know a JavaScript object consists key-value pair. Now, there can be multiple instances where we need to pass values to the object from the outside and need to change the object value accordingly or there can also be cases where we don't want to change the key value from outside of an object. This is where the JavaScript `Getter` and `Setter` comes in.

```javascript
const person = {
  firstName: "John",
  lastName: "Doe"
}
```

Here, we're assuming that we have an object that has two key-value pairs, `firstName`, and `lastName`. Now, if we want to show the full name of the `person` we can use either one of the way shown below,

We can `console.log` the full name outside the object using concatenation or using template literals, i.e,

```javascript
console.log(person.firstName + " " + person.lastName); //John Doe
```

Or

```javascript
console.log(`${person.firstName} ${person.lastName}`); //John Doe
```

If we want to `console.log` the full name at multiple places of our code, then we have to paste the same code multiple times. Which is against our `DRY(Don't Repeat Yourself)` rule. Another way can be creating a method for the object and calling the method whenever we want to get the full name.

```javascript
const person = {
  firstName: "John",
  lastName: "Doe",
  fullName () {
      return `${person.firstName} ${person.lastName}` //John Doe
  }
}
```

We can now call the method with 

```javascript
console.log(person.fullName()); //John Doe
```

If we want to get the value by calling the method like a property of the object, not like a regular function call, we need to use the `getter` method here. So, the code will be,

```javascript
get fullName () {
      return `${person.firstName} ${person.lastName}` //John Doe
  }
```

The `get` keyword in front of the method name is important. Now, we can call `fullName` using `person.fullName` only. We don't have to add the extra braces at the end. Moreover, now we can't change the value of `fullName` from the outside.

![](https://i.ibb.co/cCKRnZv/Annotation-2020-07-17-123203.png)

If we try to set the `fullName` from outside of the object, we will not get an error, rather it'll show the value set inside the object.

![](https://i.ibb.co/r7mGTVv/Annotation-2020-07-17-145022.png) 

Suppose we want pass the `fullName` value from outside of the object and want to set the `firstName` and `lastName` value according to the `fullName` value passed. If we try to initialize it using `person.fullName = "Jane Doe";` it'll not work. Here comes the `setter` method. Let's check an example,

```javascript
set fullName (val) {
    const split = val.split(" ");
    this.firstName = split[0];
    this.lastName = split[1]
  }
```

So, we're getting a value from the `val` argument and then splitting it into parts at places where the value has spaces using the JavaScript `split()` method. The `split()` method returns an `array`. We're assigning the first element of the `array` to the `firstName` key and the second element of the array to the `lastName` key. 

![](https://i.ibb.co/6nDVDBY/Annotation-2020-07-17-134043.png)

Now we can pass a value to the `fullName` method and set `firstName` and `lastName` values accordingly. Both this get and set method can be achieved with multiple functions which will be more simple, but that won't be a robust solution.

### The Full Code 🚀

```javascript
const person = {
  firstName: "John",
  lastName: "Doe",
  get fullName () {
      return `${person.firstName} ${person.lastName}`
  },
  set fullName (val) {
    const split = val.split(" ");
    this.firstName = split[0];
    this.lastName = split[1]
  }
}
```



## Why use Getter and Setter? 🐲

In object-oriented languages, an important concept is data hiding. Usually, classes have access modifiers like `public/private` which restricts the exposure of the members. One of the most important uses of `Getter` and `Setter` is to expose the functions more safely. For example, if we set only the `get` method, the value of the member can never be changed from the outside of the class. 

To learn about it in more depth, check this beautiful article [here](https://www.jackfranklin.co.uk/blog/es5-getters-setters/).

***

Originally Posted at [hashnode](https://blog.nemotivity.xyz/an-introduction-to-javascript-getters-and-setters-ckcq1o3rv003clus11w4chpk6)