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.

Examples

 

Defining a setter on new objects in object initializers

The following example define a pseudo-property current of object language. When current is assigned a value, it updates log with that value:

const language = {
  set current(name) {
    this.log.push(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.