Skip to main content
A setter is a special method that binds an object property to a function, which is automatically invoked whenever an attempt is made to assign a value to that property. It intercepts the assignment operation, acting as an accessor property rather than a standard data property.

Syntax

Setters can be defined within object literals, ES6 classes, or dynamically using Object.defineProperty(). The set keyword is used to declare the method. Object Literal:
ES6 Class:

Invocation

A setter is not invoked like a standard function. It is triggered implicitly via the assignment operator (=). The right-hand operand of the assignment is passed as the single argument to the setter method.

Technical Constraints and Behavior

  • Arity: A setter method must have exactly one parameter. Attempting to define a setter with zero or multiple parameters will throw a SyntaxError.
  • Property Descriptors: Defining a setter creates an accessor property. In the object’s property descriptor, this property will have a set attribute (pointing to the function) instead of value and writable attributes.
  • Return Value: The return value of a setter function is entirely ignored by the JavaScript engine. The result of the assignment expression is always the value that was assigned, regardless of what the setter returns.
  • Naming Collisions: An object cannot have a data property and an accessor property with the same name. To prevent infinite recursion (stack overflow), a setter must not assign a value to its own property identifier. It must mutate a separate backing property (conventionally prefixed with _ or declared as a private # field).

Dynamic Definition

To attach a setter to an existing object after its initial creation, you must use Object.defineProperty().
Tired of Poor JavaScript Skills? Fix That With Deep Grasping!Learn More