The set syntax binds an object property to a function to be called when there is an attempt to set that property.


{set prop(val) { . . . }}
{set [expression](val) { . . . }}


The name of the property to bind to the given function.
An alias for the variable that holds the value attempted to be assigned to prop.
Starting with ECMAScript 2015, you can also use expressions for a computed property name to bind to the given function.


In JavaScript, a setter can be used to execute a function whenever a specified property is attempted to be changed. Setters are most often used in conjunction with getters to create a type of pseudo-property. It is not possible to simultaneously have a setter on a property that holds an actual value.

Note the following when working with the set syntax:

A setter can be removed using the delete operator.


Defining a setter on new objects in object initializers

This will define a pseudo-property current of object language that, when assigned a value, will update log with that value:

var language = {
  set current(name) {
  log: []

language.current = 'EN';
console.log(language.log); // ['EN']

language.current = 'FA';
console.log(language.log); // ['EN', 'FA']

Note that current is not defined and any attempts to access it will result in undefined.

Removing a setter with the delete operator

If you want to remove the setter, you can just delete it:

delete o.current;

Defining a setter on existing objects using defineProperty

To append a setter to an existing object later at any time, use Object.defineProperty().

var o = {a: 0};

Object.defineProperty(o, 'b', { set: function(x) { this.a = x / 2; } });

o.b = 10; // Runs the setter, which assigns 10 / 2 (5) to the 'a' property
console.log(o.a) // 5

Using a computed property name

var expr = 'foo';

var obj = {
  baz: 'bar',
  set [expr](v) { this.baz = v; }

console.log(obj.baz); // "bar"
obj.foo = 'baz';      // run the setter
console.log(obj.baz); // "baz"


Browser compatibility

Feature Chrome Edge Firefox (Gecko) Internet Explorer Opera Safari
Basic support 1 (Yes) 2.0 (1.8.1) 9 9.5 3
Computed property names No support (Yes) 34 (34) No support No support No support
Feature Android Chrome for Android Edge Firefox Mobile (Gecko) IE Mobile Opera Mobile Safari Mobile
Basic support (Yes) (Yes) (Yes) 1.0 (1.8.1) (Yes) (Yes) (Yes)
Computed property names No support No support ? 34.0 (34.0) No support No support No support

SpiderMonkey-specific notes

  • Starting with JavaScript 1.8.1, setters are no longer called when setting properties in object and array initializers.
  • From SpiderMonkey 38 on, a setter with a rest parameter is a SyntaxError as per the ES2015 specification.

See also

© 2005–2017 Mozilla Developer Network and individual contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.