JS Getters and Setters - #10daysUnknownJSChallenge #day2

getters and setters are accessor properties for a object. getters and setters values are essentially functions which return the value when accessing the property

This article is part of my #10daysUnknownJSChallenge where I spent a very little time to explore 10 unknown topics for the series of 10 days

Example:

const obj = {  
  firstName: 'John',  
  lastName: 'Smith',  
  get fullName() { return `${this.firstName} ${this.lastName}` },  
  set fullName(fullName) { [this.firstName, this.lastName] = fullName.split(" ") }  
}  

When the getter or setter property is accessed, function is executed. We need not to call the property as a function. Just need to access as a property and it implicitly executes the function

Note:

  1. getters & setters shouldn't have the same name as other property in the object

Updating Existing object with getters & setters

Existing object can be updated with getters & setters using Object.defineProperty

const obj = {  
  firstName: 'John',  
  lastName: 'Smith'  
}  
  
Object.defineProperty(user, 'fullName', {  
  get() {  
    return `${this.firstName} ${this.lastName}`;  
  },  
  set(fullName) {  
    [this.firstName, this.lastName] = fullName.split(" ");  
  }  
});  

Note:

  1. I noted a small thing which I didn't find in any other documents I referenced for this topic.

There is a difference in visibility of the getters & setters property. Adding getter or setter property during object definition makes the accssor property visible. Where as, adding it later through Object.defineProperty makes it hidden. Yet to figure out the purpose/background of this.

const user1 = {  
  firstName: 'John',  
  lastName: 'Smith',  
  get fullName() { return `${this.firstName} ${this.lastName}`}  
}  
  
console.log(Object.keys(user1));  
// ["firstName", "lastName", "fullName"]  
  
const user2 = {  
  firstName: 'John',  
  lastName: 'Smith',  
}  

Object.defineProperty(user2, 'fullName', {  
  get() {  
    return `${this.firstName} ${this.lastName}`  
  }  
});  

console.log(Object.keys(user2))  
// ["firstName", "lastName"]