A getter looks like a property but runs a function when you read it. A setter runs a function when you assign to it.
const user = {
firstName: "Maya",
lastName: "Rao",
get fullName() {
return `${this.firstName} ${this.lastName}`;
}
};
console.log(user.fullName); // → Maya Rao
user.firstName = "Meera";
console.log(user.fullName); // → Meera Rao
fullName is computed every time you read it, so it can never get out of date. There are no parentheses when you use it.
Setters
A setter receives the assigned value, which is good for validation.
const account = {
_balance: 0,
get balance() {
return this._balance;
},
set balance(value) {
if (value < 0) {
console.log("Balance cannot be negative");
return;
}
this._balance = value;
}
};
account.balance = 100;
console.log(account.balance); // → 100
account.balance = -5; // → Balance cannot be negative
console.log(account.balance); // → 100
The underscore in _balance is only a convention that says “treat this as internal”. The language does not enforce it (use private fields in classes for real privacy).
A getter without a setter is read-only
const circle = {
radius: 5,
get area() { return Math.round(Math.PI * this.radius ** 2); }
};
circle.area = 999; // ignored in normal (sloppy) mode, an error in strict mode
console.log(circle.area); // → 79
Getters in classes
You will use them most inside classes, see Getters and Setters in Classes.
When to use them
- A value that is derived from other values (full name, total, area).
- Validating or transforming data when it is assigned.
Do not use them for slow work, because they look like cheap property reads. Use a method (calculateTotal()) when the work is expensive or has side effects.