JavaScriptMedium
What are JavaScript object getters and setters for?
By FrontendPro Editorial Team Updated 8/8/2026
#JavaScript
Answer
JavaScript object getters and setters are used to control access to an object's properties. They provide a way to encapsulate the implementation details of a property and define custom behavior when getting or setting its value.
Getters and setters are defined using the get and set keywords, respectively, followed by a function that is executed when the property is accessed or assigned a new value.
Here's a code example demonstrating the use of getters and setters:
js
const person = {
_name: "John Doe", // Private property
get name() {
// Getter
return this._name;
},
set name(newName) {
// Setter
if (newName.trim().length > 0) {
this._name = newName;
} else {
console.log("Invalid name");
}
},
};
// Accessing the name property using the getter
console.log(person.name); // Output: 'John Doe'
// Setting the name property using the setter
person.name = "Jane Smith"; // Setter is called
console.log(person.name); // Output: 'Jane Smith'
person.name = ""; // Setter is called, but the value is not set due to validation
console.log(person.name); // Output: 'Jane Smith'
