liveBook · Manning

Computed property name

As explained in Get Programming with JavaScript Next: New features of ECMAScript 2015, 2016, and beyond

An object-literal form in which a property key is evaluated from an expression rather than written as a fixed identifier or string literal.

When a property key arrives as a variable, writing `{ name: value }` creates a property literally named `name`. A computed property name evaluates an expression in square brackets, so `{ [name]: value }` uses the value stored in `name` as the key. section 12.3

function setValue(name, value) {
  stateManager.update({
    [name]: value
  });
}

const [name, value] = otherLibrary.operate();
setValue(name, value);

Use a computed key to create the update object directly, without first making an empty object and assigning its property. section 12.3

The bracket syntax works like assigning a dynamic property after an object is created. In the color example, `[property]` creates `color`; `eyes.property` looks for a separate property literally named `property`. section 12.3

 const property = 'color';
 const eyes = { [property]: 'green' };
console.log(eyes.property, eyes.color);

Compare dot access with the computed key: the object has a `color` property, not a `property` property. section 12.3

How Get Programming with JavaScript Next: New features of ECMAScript 2015, 2016, and beyond covers it

How deep it goes
Works through dynamic-key assignment and its object-literal equivalent, without delving into language internals.
Examples
Uses a state-manager update function and a color property to demonstrate dynamic keys.
What it assumes
Uses object literals and bracket notation to explain dynamic properties and contrasts them with literal keys.
What you can do after
Build it from scratch: create an object with a property key supplied at runtime.
How it connects
Connects object literals with bracket notation and, in symbol-based hooks, symbols.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Get Programming with JavaScript Next: New features of ECMAScript 2015, 2016, and beyond. The section links point to the parts of the book it draws on.