Skip to main content

Documentation Index

Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt

Use this file to discover all available pages before exploring further.

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:
const entity = {
  _internalState: null,
  
  set state(value) {
    this._internalState = value;
  }
};
ES6 Class:
class Entity {
  #internalState = null; // Private field backing the setter

  set state(value) {
    this.#internalState = value;
  }
}

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.
const instance = new Entity();

// Triggers the setter, passing 'active' as the argument
instance.state = 'active'; 

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().
const dynamicEntity = { _count: 0 };

Object.defineProperty(dynamicEntity, 'count', {
  set(value) {
    this._count = Number(value);
  },
  enumerable: true,
  configurable: true
});

dynamicEntity.count = "5"; // Invokes the dynamically defined setter
Master JavaScript with Deep Grasping Methodology!Learn More