Back to results for “Property Descriptors & Immutability”
JavaScript › Destructuring, Spread & Rest

How do computed property names interact with object destructuring?

Advanced

Answer

Wrapping an expression in square brackets inside a destructuring pattern lets you extract a property whose NAME is stored in a variable, rather than being a fixed identifier known ahead of time.
const key = 'name';
const { [key]: value } = { name: 'Sam' };
console.log(value); // 'Sam'
Real-world example Extracting a dynamically-named field, such as a form field whose key comes from configuration data.

Common follow-ups: Is this the same mechanism used for computed property names in object literals?