Build a property name from another value.

Computed Properties

computed_property.js
const field = "height";
const amount = 5;
const value = ({ [field]: amount + 1 })[field];
const message = field + "=" + value;

console.log("field=" + field);
console.log("value=" + value);
console.log("message=" + message);

Name the Field at Runtime

  1. field starts as height.
  2. amount starts as 5.
  3. { [field]: amount + 1 } creates a height property.
  4. Reading [field] returns 6. | Name part | Value | | --- | --- | | field | height | | amount + 1 | 6 | | record[field] | 6 |
computed-property A computed property name goes inside brackets in an object literal. It lets a program decide the property name while the object is being created.

Exercise: computed_property.js

Create an object with a computed property name and print the selected value