Getters and Setters
Getters and setters let you define methods that look like properties. When you access a getter, it runs a function. When you set a value through a setter, it runs a function. This gives you control over how values are read and written.
class Circle {
constructor(radius) {
this.radius = radius;
}
get area() {
return Math.PI * this.radius ** 2;
}
set radius(value) {
if (value < 0) throw new Error("Radius can't be negative");
this._radius = value;
}
get radius() {
return this._radius;
}
}
const c = new Circle(5);
console.log(c.area); // 78.54 β looks like a property!
c.radius = 10; // Calls the setter
Why Use Getters and Setters?
They let you add validation, computed values, or side effects without changing theε€ι¨ API of your class. Code that uses your class doesn't need to know there's logic behind the scenes.
class Person {
#firstName;
#lastName;
constructor(first, last) {
this.#firstName = first;
this.#lastName = last;
}
get fullName() {
return `${this.#firstName} ${this.#lastName}`;
}
set fullName(name) {
const [first, last] = name.split(" ");
this.#firstName = first;
this.#lastName = last;
}
}
const person = new Person("John", "Doe");
console.log(person.fullName); // "John Doe"
person.fullName = "Jane Smith";
console.log(person.fullName); // "Jane Smith"
Getters with Computed Properties
Getters are perfect for computed values that are derived from other data. They calculate on the fly, so you always get the current value.
class ShoppingCart {
items = [];
get total() {
return this.items.reduce((sum, item) => sum + item.price, 0);
}
get count() {
return this.items.length;
}
}
const cart = new ShoppingCart();
cart.items.push({ name: "Shirt", price: 30 });
cart.items.push({ name: "Pants", price: 50 });
console.log(cart.total); // 80
console.log(cart.count); // 2
Try it Yourself β
Property Definitions
You can also define getters and setters using Object.defineProperty. This is useful for objects created outside of classes.
const temperature = {
_celsius: 0,
};
Object.defineProperty(temperature, "fahrenheit", {
get() {
return this._celsius * 9 / 5 + 32;
},
set(f) {
this._celsius = (f - 32) * 5 / 9;
},
});
temperature.fahrenheit = 212;
console.log(temperature._celsius); // 100
Summary
Getters and setters give you property-like access with method-like behavior. Use them for validation, computed values, and keeping your class API clean.