Getters and setters are special methods in JavaScript objects that allow controlled access to object properties.

💡 What are Getters & Setters?
Getters allow you to define a method that runs when a property is accessed. Setters run when a property is assigned a value. This lets you add logic during property access or update.
They help keep properties private or computed, provide validation, or trigger side effects.
| Getter | Setter |
|---|---|
get propName() { ... } |
set propName(value) { ... } |
📌 Deep Dive: Using Getters & Setters
const person = {
firstName: 'John',
lastName: 'Doe',
get fullName() {
return `${this.firstName} ${this.lastName}`;
},
set fullName(name) {
const parts = name.split(' ');
this.firstName = parts[0];
this.lastName = parts[1] || '';
}
};
console.log(person.fullName); // John Doe
person.fullName = 'Jane Smith';
console.log(person.firstName); // Jane
console.log(person.lastName); // Smith
Jane
Smith
💡 Why use Getters & Setters?
- Encapsulation: Hide internal representation of data.
- Validation: Validate or modify data before setting.
- Computed properties: Calculate values on the fly.
- Debugging: Easily log or watch property access.
⚠️ Important
Getters should not have side effects and should return a value quickly. Setters must accept exactly one argument.
| Feature | Regular Property | Getter/Setter |
|---|---|---|
| Access | Direct value | Runs code |
| Modification | Direct assignment | Runs code with validation |
| Computed | No | Yes |
| Side Effects | Possible | Not recommended for getters |
💡 Quick Tip
You can define getters/setters in object literals, classes, or via Object.defineProperty().
📌 Deep Dive: Getters & Setters in Classes
class Rectangle {
constructor(width, height) {
this.width = width;
this.height = height;
}
get area() {
return this.width * this.height;
}
set area(value) {
throw new Error('Area is read-only!');
}
}
const rect = new Rectangle(4, 5);
console.log(rect.area); // 20
// rect.area = 30; // Error: Area is read-only!
⚠️ Avoid Infinite Loops
Inside setters or getters, be careful not to assign or access the same property directly; use a different property name to avoid recursion.
Quick Knowledge Check
Test what you just learned
Question 1 of 2
What happens when you access an object property that has a getter method defined?
Question 2 of 2
Which of the following is a recommended practice when writing getters?
Loading results...