liveBook · Manning

Setter

As explained in Secrets of the JavaScript Ninja, Third Edition

A setter is a property accessor that receives a value when the property is assigned.

A setter is an accessor that runs when a property is assigned. It lets an object keep direct property syntax while performing work such as logging, validation, or updating an internal representation. section 9.1 section 9.1.1

In an object literal or class, define one with the set keyword before the property name. Assigning to that property calls the setter; it is not called like an ordinary function. Methods named setX are only setters by convention. To add an accessor to an existing object, use Object.defineProperty. section 9.1.1

Listing 9.1 Defining getters and setters in an object literal
const ninjaCollection = {
  ninjas: ["Yoshi", "Kuma", "Hattori"],
  get firstNinja() { #A
    console.log(`Getting firstNinja: ${this.ninjas[0]}`); #A
    return this.ninjas[0]; #A
  }, #A
  set firstNinja(newNinja: string) { #B
    console.log(`Setting firstNinja: ${newNinja}`); #B
    this.ninjas[0] = newNinja; #B
  }, #B
};

console.assert( #C
  ninjaCollection.firstNinja === "Yoshi", #C
  "Yoshi is the first ninja", #C
); #C

ninjaCollection.firstNinja = "Hachi"; #D

console.assert( #E
  ninjaCollection.firstNinja === "Hachi" && #E
    ninjaCollection.ninjas[0] === "Hachi", #E
  "Now Hachi is the first ninja", #E
); #E

The setter updates the first item when firstNinja is assigned, while reads call the paired getter. section 9.1.1

How Secrets of the JavaScript Ninja, Third Edition covers it

How deep it goes
Explains accessor syntax, assignment-triggered calls, and dynamic definition with Object.defineProperty.
Examples
Demonstrates a ninja collection whose setter replaces the first array item and logs the assignment.
What it assumes
Assumes familiarity with reading and assigning object properties, and distinguishes accessor syntax from conventionally named methods.
What you can do after
Apply setter syntax in an object literal or class, or add an accessor to an existing object with Object.defineProperty.
How it connects
Connects setters with getters, object properties, object literals, classes, and Object.defineProperty.

Also explained in

Compare how 2 books explain setter →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Secrets of the JavaScript Ninja, Third Edition. The section links point to the parts of the book it draws on.