liveBook · Manning

Computed property

As explained in Secrets of the JavaScript Ninja, Second Edition

A property whose value is derived on access or assignment rather than stored as an independent data field.

A computed property derives its value when read instead of storing an independent value. Its getter can read other properties, while its setter can update them when an assignment is made. section 8.1.3

Listing 8.6. Defining computed properties
const shogun = {
  name: "Yoshiaki",
  clan: "Ashikaga",
  get fullTitle(){                                          #A
    return this.name + " " + this.clan;                     #A
  },                                                        #A
  set fullTitle(value) {                                    #B
    const segments = value.split(" ");                      #B
    this.name = segments[0];                                #B
    this.clan = segments[1];                                #B
  }                                                         #B
};

assert(shogun.name === "Yoshiaki", "Our shogun Yoshiaki");      #C
assert(shogun.clan === "Ashikaga", "Of clan Ashikaga");         #C
assert(shogun.fullTitle === "Yoshiaki Ashikaga",                #C
       "The full name is now Yoshiaki Ashikaga");               #C

shogun.fullTitle = "Ieyasu Tokugawa";                           #D
assert(shogun.name === "Ieyasu", "Our shogun Ieyasu");          #D
assert(shogun.clan === "Tokugawa", "Of clan Tokugawa");         #D
assert(shogun.fullTitle === "Ieyasu Tokugawa",                  #D
       "The full name is now Ieyasu Tokugawa");                 #D

The shogun’s fullTitle getter joins name and clan; its setter splits an assigned title and updates those properties. section 8.1.3

A method such as getFullTitle could provide the same value, but a property can make a value dependent on an object’s state clearer to use. section 8.1.3

How Secrets of the JavaScript Ninja, Second Edition covers it

How deep it goes
Explains getter concatenation and setter splitting into underlying properties, covering both reads and writes.
Examples
Uses a shogun’s fullTitle, derived from name and clan and assigned by splitting a title string.
What you can do after
Evaluate/understand how to expose derived object state as a property and map assignments back to its component properties.
How it connects
Connects computed properties to getters, setters, and object properties.

Also explained in

Compare how 2 books explain computed property →

Related concepts

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