setter
A setter is a function bound to an object property that runs whenever code assigns to that property, so the assignment passes its value to the function instead of storing it directly.
A property with a setter is an accessor property, usually paired with a getter that reads the value back. An assignment that reaches it calls the setter with the assigned value as its only argument and this set to the object the assignment started from. The setter’s return value is discarded.
Most setters come from the set syntax in an object literal or a class body, and Object.defineProperty() can add one to an existing object. A class setter lives on the class’s prototype, so assignments on every instance reach it through the prototype chain.
An accessor property with a getter and no setter can’t be assigned to. Sloppy-mode code ignores the assignment without an error, while strict-mode code, including every class body and module, throws a TypeError.
Example
Say a thermostat class keeps its target temperature a whole number between ten and thirty degrees, whatever value code assigns:
> class Thermostat {
… #target = 20;
… get target() {
… return this.#target;
… }
… set target(degrees) {
… this.#target = Math.min(Math.max(Math.round(degrees), 10), 30);
… }
… }
undefined
> const thermostat = new Thermostat();
undefined
> thermostat.target = 22.6
22.6
> thermostat.target
23
> thermostat.target = 45
45
> thermostat.target
30
> Object.hasOwn(thermostat, "target")
false
Each assignment runs the setter, which rounds and clamps the value before storing it. The assignment expressions still evaluate to 22.6 and 45, the values on their right side, because the setter’s return value never reaches the caller. The instance has no own target property, since the setter lives on Thermostat.prototype.
Say an order object exposes its total through a getter only, and some code tries to reset that total. Modules run in strict mode, so the assignment throws:
order-total.mjs
const order = {
prices: [12, 30],
get total() {
return this.prices.reduce((sum, price) => sum + price, 0);
},
};
try {
order.total = 0;
} catch (error) {
console.log(`${error.name}: ${error.message}`);
}
console.log(`Total: ${order.total}`);
Running the file shows the error and the unchanged total:
$ node order-total.mjs
TypeError: Cannot set property total of #<Object> which has only a getter
Total: 42
Related Resources
Course
The JavaScript Object Model: Properties, Descriptors, and Freezing
Port a print shop's Python proof card export to JavaScript, and learn to control what an object owns, computes, lists, and lets you change, with descriptors, symbols, and freezing.
For additional information on related topics, take a look at the following resources:
Have a question about this? Mentor AI can show you examples, compare related terms, and point you to tutorials.
By Leodanis Pozo Ramos • Updated Nov. 19, 2026