JavaScript Getters & Setters
Getters and setters (together: accessors) are methods that look like ordinary properties from the outside. Reading the property calls the getter; assigning to it calls the setter. They let you compute values on the fly, validate input, and keep a clean, property-style interface.
Getters: computed properties
Define a getter with the get keyword. Access it without parentheses:
const person = {
firstName: "Grace",
lastName: "Hopper",
get fullName() {
return `${this.firstName} ${this.lastName}`;
},
};
console.log(person.fullName); // no () — looks like a property
person.lastName = "Brewster";
console.log(person.fullName); // always up to date
console.log(person);Grace Hopper
Grace Brewster
{ firstName: 'Grace', lastName: 'Brewster', fullName: [Getter] }
The value is computed every time it's read, so it can never get out of sync with the data it depends on.
Setters: controlled assignment
A setter receives the assigned value as its single parameter. Use it to validate, normalise, or update related data:
const thermostat = {
_celsius: 20,
get celsius() {
return this._celsius;
},
set celsius(value) {
if (typeof value !== "number" || value < 5 || value > 30) {
throw new RangeError(`Temperature ${value} is out of range (5–30)`);
}
this._celsius = value;
},
get fahrenheit() {
return this._celsius * 1.8 + 32;
},
set fahrenheit(value) {
this.celsius = (value - 32) / 1.8; // reuse the validation
},
};
thermostat.celsius = 22;
console.log(thermostat.celsius, thermostat.fahrenheit);
thermostat.fahrenheit = 68;
console.log(thermostat.celsius);
try {
thermostat.celsius = 45;
} catch (err) {
console.log(err.message);
}22 71.6
20
Temperature 45 is out of range (5–30)
The leading underscore in _celsius is only a convention meaning "internal, please don't touch" — anyone can still change it. In classes you can use truly private #fields instead.
Accessors in classes
Getters and setters work the same way in classes, and pair naturally with private fields:
class Rectangle {
#width;
#height;
constructor(width, height) {
this.width = width; // goes through the setter
this.height = height;
}
get width() { return this.#width; }
set width(v) { this.#width = Rectangle.#positive(v, "width"); }
get height() { return this.#height; }
set height(v) { this.#height = Rectangle.#positive(v, "height"); }
get area() { return this.#width * this.#height; } // read-only: no setter
static #positive(v, name) {
if (!(v > 0)) throw new RangeError(`${name} must be positive, got ${v}`);
return v;
}
}
const r = new Rectangle(4, 3);
console.log(r.width, r.height, r.area);
r.width = 10;
console.log(r.area);
try {
r.area = 100; // no setter -> error in strict mode
} catch (err) {
console.log(err.message);
}
try {
r.height = -2;
} catch (err) {
console.log(err.message);
}4 3 12
30
Cannot set property area of #<Rectangle> which has only a getter
height must be positive, got -2
A getter without a setter creates a read-only property. In strict mode (modules and classes) assigning to it throws.
Object.defineProperty
Accessors can also be added to an existing object with Object.defineProperty, which gives fine control over whether the property is enumerable or configurable:
const cart = { items: [12, 8, 30] };
Object.defineProperty(cart, "total", {
get() {
return this.items.reduce((sum, p) => sum + p, 0);
},
enumerable: false, // hidden from Object.keys and JSON
});
console.log(cart.total);
cart.items.push(5);
console.log(cart.total);
console.log(Object.keys(cart), JSON.stringify(cart));50
55
[ 'items' ] {"items":[12,8,30,5]}
Lazy getters
A getter can compute an expensive value the first time it's read, then replace itself with a plain data property — the result is cached for all later reads:
const report = {
get stats() {
console.log(" (computing stats…)");
const value = { count: 3, mean: 42 };
Object.defineProperty(this, "stats", { value }); // replace the getter
return value;
},
};
console.log(report.stats.mean);
console.log(report.stats.count); // no recomputation (computing stats…)
42
3
When to use accessors
| Good use | Avoid |
|---|---|
derived values (fullName, area, total) |
slow work that callers don't expect from a "property" |
| validation on assignment | surprising side effects (network calls, logging users out) |
| keeping a stable API while internals change | setters with no matching getter |
Tip: If reading a property is expensive or can fail, a normal method like
calculateTotal()communicates that better than a getter.
Test yourself
How do you read a getter named total on order?
- order.total()
- order.total
- order.get("total")
- order.getTotal
What happens when you assign to a getter-only property in strict mode?
- The value is stored anyway
- It is silently ignored
- A TypeError is thrown
- The getter is removed
How many parameters does a setter take?
- None
- Exactly one
- Two
- Any number