Open In App

JavaScript Object Accessors

There are two keywords that define the accessors functions: a getter and a setter for the fullName property. When the property is accessed, the return value from the getter is used. When a value is set, the setter is called and passed the value that was set.

JavaScript Getter (The get Keyword)

Example: This example describes the use of the lang() property to get the value of the language property.






// Create an object:
const person = {
    name: "geeksforgeeks",
    get lang() {
        return this.name;
    }
};
 
// Display data from the
//object using a getter
console.log(person.name);

Output
geeksforgeeks

JavaScript Setter (The set Keyword)

Example: This example describes the use of the lang() property to set the value of the language property.






// Create an object:
const person = {
    name: "geeksforgeeks",
 
    set lang(value) {
        return this.name;
    }
};
 
// Display data from the
//object using a getter
console.log(person.name);

Output
geeksforgeeks

Note: Getters and Setters are not supported in Internet Explorer 8.

Reasons to use Getters and Setters

Data Quality

The Getters and Setters are used to secure better data quality. In the given example below, using the lang property, the lowercase value of the language is returned.

Example: This example uses the lang property and it returns the lowercase value of the language.




const person = {
    language: "Geeksforgeeks",
    get lang() {
        return this.language.toLowerCase();
    }
};
// Display data from the
//object using a getter
console.log(person.lang);

Output
geeksforgeeks

Article Tags :