How do getters and setters work inside a class?
Short answer
get and set define accessor properties that look like plain fields from the outside but run custom logic on read or write — useful for validation or computed values without changing how consumers interact with the object.
Advertisement
AModel answer
get and set define accessor properties that look like plain fields from the outside but run custom logic on read or write — useful for validation or computed values without changing how consumers interact with the object.
class Temperature {
#celsius = 0;
get fahrenheit() { return this.#celsius * 9/5 + 32; }
set fahrenheit(f) { this.#celsius = (f - 32) * 5/9; }
}
const t = new Temperature();
t.fahrenheit = 98.6;Real-world example
Exposing a computed fullName getter derived from firstName and lastName fields.
Likely follow-ups
- Do getters/setters count as own properties when you use Object.keys()?
Related topics