First, a setter is used to set the value of a property. A setter gets called each time the value of the property is changed. In other words, it executes a function for each time a property used inside the setter function is changed. Take a look at the following code:
In the object foo, the setter cal will be called each time the property a is changed. As an output, you will get 13 printed. While creating a setter, you need to follow these rules:
- A setter name could be either string or number.
- A setter must have exactly one input parameter.
- There should be only one setter with the same identifier in an object
- You can remove a setter using the delete operator
For other examples of a setter, let’s take a look at the following code:
For the above code snippet as output, Hello Jason will be printed. You can also add the setter to an existing object using Object.defineProperty. Let’s say that you have an object foo:
Now to add a setter for the existing object foo , use Object.defineProperty.