Saturday, April 11, 2020

Getter and Setter in JS

Let us suppose we have an object called User like this:
1
2
3
4
const user = {
    firstName: 'A',
    lastName: 'B',
}

Now suppose we want to return the full name of the function it will something be like this:

1
console.log(`${user.firstName} ${user.lastName}`)

But this is a naive approach and in case if we have to add something extra in the statement, we have to change every where, instead the better way is to give a function that will return this expression/value like:

1
2
3
4
5
6
7
8
9
const user = {
    firstName: 'A',
    lastName: 'B', 
    fullName () { // previous version was like fullName: function () {...} but changed in ES6
        return `${this.firstName} ${this.lastName}`
    }
}

console.log(${user.fullName())

Now this is good but:
  1. what if you want to use it as a field and not as a function, I mean, I want to use it something like: console.log(${user.fullName).
  2. And we want to set the value of firstName and lastName on the basis of value we are going to pass to fullName like user.fullName = 'Javascript rocks' 
For that we have 2 keywords called get and set and the use is like this:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
const user = {
    firstName: 'A',
    lastName: 'B', 
    get fullName () {
        return `${this.firstName} ${this.lastName}`
    }

    set fullName (value) {
        const tokens = value.split(' ');
        this.firstName = tokens[0];
        this.lastName = tokens[1];
    }
}

console.log('Before set', ${user.fullName})

user.fullName = 'Javascript Rocks'.

console.log('After set', ${user.fullName})

Here in this code there are 2 keywords we have seen,

  • get = for accessing the property (at line 4)
  • set = for setting the property (at line 8)
These 2 keywords make the function as a property and that is the reason at line 15 and line 19 we have accessed the fullName without the parenthesis.

That's it, its awesome right :)

Happy Coding :)

For reference, please check out this: https://www.youtube.com/watch?v=bl98dm7vJt0

2 comments: