JavaScript Object Accessors
14 April 2025 | Category: JavaScript
Object accessors allow you to control how properties are accessed and modified in JavaScript. They provide a way to define computed or protected properties using special methods called getters and setters.
đ§ Why Use Accessors?
Accessors are useful when you:
- Want to control or customize property access
- Need to compute a value on the fly
- Want to validate or restrict data updates
đ„ Getters
A getter is a method that is called when you try to access a property.
đ§Ș Syntax:
const obj = {
get propName() {
// logic here
return value;
}
};
đ§© Example:
const person = {
firstName: "Jane",
lastName: "Smith",
get fullName() {
return `${this.firstName} ${this.lastName}`;
}
};
console.log(person.fullName); // Jane Smith
â
Note: You access it like a property, not a function (person.fullName
, not person.fullName()
).
đ€ Setters
A setter is a method that is called when a property value is assigned.
đ§Ș Syntax:
const obj = {
set propName(value) {
// logic here
}
};
đ§© Example:
const user = {
firstName: "John",
lastName: "Doe",
set fullName(name) {
const parts = name.split(" ");
this.firstName = parts[0];
this.lastName = parts[1];
}
};
user.fullName = "Alice Cooper";
console.log(user.firstName); // Alice
console.log(user.lastName); // Cooper
đ Full Example with Getter and Setter
const product = {
_price: 0,
get price() {
return `$${this._price.toFixed(2)}`;
},
set price(value) {
if (value < 0) {
console.error("Price must be positive");
} else {
this._price = value;
}
}
};
product.price = 25.5;
console.log(product.price); // $25.50
đ Note:
- Prefix like
_price
is often used to represent the private version of a property.
đ Advantages of Using Accessors
- Encapsulation: Hide internal implementation
- Validation: Validate values before setting
- Read-only/Write-only: Control access to sensitive data
- Computed Properties: Return dynamic values
â Caution
- Getters must return a value, or youâll get
undefined
. - Avoid heavy logic in accessors to keep performance fast.
- Donât make accessors do unexpected things (like modifying unrelated data).
đ§ Bonus: Define Accessors with Object.defineProperty()
const student = { name: "Tom" };
Object.defineProperty(student, "greeting", {
get() {
return `Hello, ${this.name}`;
}
});
console.log(student.greeting); // Hello, Tom