Getters and Setters
In JavaScript classes, get and set keywords allow us to define special methods that act like standard properties from the outside, but execute custom logic on the inside.
The Getter (get)
A getter allows you to format or compute a value dynamically when someone tries to access a property.
class User {
constructor(name, age) {
this._name = name;
this.age = age;
}
// Acts like a property, but runs as a function
get name() {
return this._name.toUpperCase();
}
}
const lane = new User("Lane", 30);
// Notice there are no parentheses () when calling it!
console.log(lane.name); // Output: "LANE"
Note: We rename the internal property to _name to prevent a naming collision and infinite loop with the getter itself.
The Setter (set)
A setter lets you intercept an assignment to validate data or trigger side effects before updating the internal value.
class User {
constructor(name, age) {
this.name = name;
// We expect the setter to handle validation later
this._age = age;
}
get age() {
return this._age;
}
set age(value) {
if (value < 0) {
throw new Error("Age can't be negative.");
}
this._age = value;
}
}
const lane = new User("Lane", 29);
// Triggers the setter method
lane.age = -5; // Throws Error: "Age can't be negative."
A Word of Caution
While powerful, getters and setters can make code confusing. When developers interact with what looks like a basic property (lane.age = 50), they expect a simple assignment, not complex logic or thrown errors.
Unless you are working in specific reactive environments (like Vue.js or MobX), it is often clearer to write explicit validation methods like setAge(50). Use getters and setters sparingly and intentionally.