CKTIS / JavaScript
set — defining a property setter
`set` defines a setter: a function invoked when a property is assigned. It is part of accessor syntax, not a word reserved in every context.
Version: ECMAScript and Web APIs; exact feature edition and browser support reviewed per entry; Node 24 in repository does not prove browser API support
Syntax
({ set property(value) { /* body */ } })
class Example { set property(value) { /* body */ } }set property(value) { ... } defines a setter in an object literal or class. Assigning obj.property = value invokes it with the assigned value. set is not a reserved word: outside this syntax, it can be an ordinary identifier.
A setter must have exactly one formal parameter; a rest parameter is not allowed. It can coexist with a get getter for the same property. Reading a property that has only a setter returns undefined.
Store state under another name: writing this.property = value inside the setter for property invokes that setter again, causing recursion. A setter's return value is ignored; an assignment expression evaluates to the assigned value.
In the example, the setter stores twice the number in _value, and the getter reads it. The _ prefix is only a convention and does not provide privacy.
Examples
const counter = {
_value: 0,
set value(next) {
this._value = next * 2;
},
get value() {
return this._value;
}
};
const assigned = (counter.value = 4);
console.log(counter.value);
console.log(assigned);Result
8 4
The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.