JavaScript Interview Question #113
What are getters and setters?
Closures, Prototypes, Classes & Advanced Functions Mid-Level Intermediate
Quick Interview Answer
Getters and setters define property-like access backed by functions. A getter runs when the property is read, while a setter runs when the property is assigned.
Detailed Explanation
Getters and setters define property-like access backed by functions. A getter runs when the property is read, while a setter runs when the property is assigned.
They are useful for computed values, validation, normalization, or controlled access. Because callers use property syntax, getters should generally avoid surprising side effects or expensive hidden work.
Code Example
class Product {
constructor(price) {
this._price = price;
}
get price() {
return this._price;
}
set price(value) {
if (value < 0) {
throw new Error("Price cannot be negative");
}
this._price = value;
}
}