DEV Community

Cover image for What is Getters and Setters in JavaScript
Vetrivel p
Vetrivel p

Posted on

What is Getters and Setters in JavaScript

Before go the Getters and Setters, you must learn about JS Objects.

Getters and Setters allow you to define Object Accessors.

In JavaScript, Accessor properties are methods that get or set the value of an object.

get - to define a getter method to get the property value.
set - to define a setter method to set the property value.

let person ={
    firstName:"Title", // Data Properties
    lastName: "Card",
   /* fullName: () => {
        return `${person.firstName} ${person.lastName}`;
    }*/

   fullName(){ // ES6 Features
    return `${person.firstName} ${person.lastName}`; // Template literals
} 

};
console.log(person.fullName());
//console.log(person.firstName + ' ' + person.lastName);
Enter fullscreen mode Exit fullscreen mode

Getters is used to get the data(Keyword-get)
Setters is used to set the data(Keyword-set)

let person ={
    firstName:"Title", // Data Properties
    lastName: "Card",
   /* fullName: () => {
        return `${person.firstName} ${person.lastName}`;
    }*/

    // Getters is used to get the data

   get fullName(){ 
    return `${person.firstName} ${person.lastName}`; 
}, 

// Setters is used to set the data


set fullName(value){
   let values = value.split(" ");
   //console.log(values)
   this.firstName = values[0];
   this.lastName = values[1];
   // If the name is single word (only firstName)
   //this.lastName = values[1] ?? "";

}
};
person.fullName = "Name Tag"
console.log(person.fullName);
Enter fullscreen mode Exit fullscreen mode

Why Using Getters and Setters?

  1. It gives simpler syntax
  2. It allows equal syntax for properties and methods
  3. It can secure better data quality
  4. It is useful for doing things behind-the-scenes

Top comments (0)