JavaScript Object Accessors
Last Updated :
26 Jul, 2023
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
const person = {
name: "geeksforgeeks" ,
get lang() {
return this .name;
}
};
console.log(person.name);
|
JavaScript Setter (The set Keyword)
Example: This example describes the use of the lang() property to set the value of the language property.
Javascript
const person = {
name: "geeksforgeeks" ,
set lang(value) {
return this .name;
}
};
console.log(person.name);
|
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();
}
};
console.log(person.lang);
|
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...