In JavaScript, getters and setters are special methods that allow you to define how properties of an object are accessed (get) and updated (set). They help control and customize access to object properties.
๐น Getter (get)
- Used to retrieve the value of a property.
- Defined using the
getkeyword inside an object or class. - Looks like a normal property when accessed, but under the hood, itโs a function.
const person = {
firstName: "Himanshu",
lastName: "Sharma",
// Getter
get fullName() {
return this.firstName + " " + this.lastName;
}
};
console.log(person.fullName); // "Himanshu Sharma"
๐ Notice: You donโt call it like a function (person.fullName()), you access it like a property (person.fullName).
๐น Setter (set)
- Used to set/update the value of a property.
- Defined using the
setkeyword. - Accepts exactly one parameter.
const person = {
firstName: "Himanshu",
lastName: "Sharma",
// Getter
get fullName() {
return this.firstName + " " + this.lastName;
},
// Setter
set fullName(name) {
const parts = name.split(" ");
this.firstName = parts[0];
this.lastName = parts[1];
}
};
person.fullName = "Rahul Verma";
console.log(person.firstName); // "Rahul"
console.log(person.lastName); // "Verma"
๐น In Classes
You can also use getters and setters in ES6 classes:
class Rectangle {
constructor(width, height) {
this.width = width;
this.height = height;
}
// Getter
get area() {
return this.width * this.height;
}
// Setter
set area(value) {
this.width = Math.sqrt(value);
this.height = Math.sqrt(value);
}
}
const rect = new Rectangle(4, 9);
console.log(rect.area); // 36 (getter)
rect.area = 49; // (setter modifies width & height)
console.log(rect.width); // 7
console.log(rect.height);// 7
โ Benefits of Getters and Setters
- Encapsulation โ Control access to properties.
- Validation โ Set rules before assigning values.
- Computed Properties โ Dynamically generate values.
- Abstraction โ Hide internal implementation.
