Open In App

JavaScript Object Accessors

Last Updated : 26 Jul, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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.

Javascript




// 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.

Javascript




// 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

  • The syntax for properties and methods are equal.
  • Used for doing things behind the scenes.
  • They can secure better data quality.
  • The syntax of this is simpler.

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.

Javascript




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


Output

geeksforgeeks


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads