Skip to content

set

In JavaScript, set is a contextual keyword that defines a setter, a function that runs when code assigns a value to a property. It works in class bodies and object literals, where set name(value) { ... } makes name an accessor property instead of a data property. The keyword is unrelated to the Set built-in.

A setter takes exactly one parameter, which receives the assigned value. That parameter can have a default, but it can’t be a rest parameter. Pairing set with get under the same name gives the property both a read and a write side. A property with only a setter reads as undefined.

Object literal setters are enumerable own properties. Class setters live on the class’s .prototype object, or on the class itself when marked static, and aren’t enumerable. Outside these positions, set is an ordinary identifier.

Setters in object literals date from ES5, and class setters from ES2015. Private setters, written set #name(), were added in ES2022 and are Baseline Widely available.

JavaScript set Keyword Syntax

A setter takes exactly one parameter:

Language: JavaScript Syntax
set <name>(<parameter>) {
  <statements>
}
set [<expression>](<parameter>) {
  <statements>
}

In a class, the setter can also be static or private.

JavaScript set Keyword Examples

A setter validates each value assigned to celsius:

Language: JavaScript
> class Thermostat {
…   #celsius = 20;
…   get celsius() {
…     return this.#celsius;
…   }
…   set celsius(value) {
…     if (value < 5 || value > 30) {
…       throw new RangeError(`Out of range: ${value}`);
…     }
…     this.#celsius = value;
…   }
… }
undefined
> const thermostat = new Thermostat();
undefined

> thermostat.celsius = 23;
23
> thermostat.celsius
23

> try {
…   thermostat.celsius = 40;
… } catch (error) {
…   error.message;
… }
'Out of range: 40'
> thermostat.celsius
23

Each assignment runs the setter, which checks the value before storing it in a private field. The out-of-range value throws a RangeError and leaves the field unchanged.

An object literal can define a setter without a getter:

Language: JavaScript
> const settings = {
…   history: [],
…   set theme(name) {
…     this.history.push(name);
…   },
… };
undefined

> settings.theme = "dark";
'dark'
> settings.theme
undefined
> settings.history
[ 'dark' ]

The setter records each assigned value, but reading settings.theme returns undefined because the property has no getter.

JavaScript set Keyword Use Cases

  • Validating a value before storing it
  • Keeping a private field behind a public property name
  • Updating derived state whenever a property changes
  • Logging or reacting to assignments

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. 4, 2026