Objects and Properties
Computed Properties
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
fieldstarts asheight.amountstarts as5.{ [field]: amount + 1 }creates aheightproperty.- Reading
[field]returns6. | 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