Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / JavaScript

Object destructuring and shorthand

Object destructuring reads properties from an existing value. Property shorthand goes the other way: it uses variables to create same-named properties on a new object.

Version: ECMAScript 2024 and the current web platform; runtime support varies

Syntax

const { name, theme = "light" } = source;
const { name: displayName, [key]: selected, ...rest } = source;
let currentName;
({ name: currentName } = source);
const view = { displayName, theme };
const explicitView = { displayName: displayName, theme: theme };

Object destructuring and shorthand use similar braces for different jobs. In const { name } = source;, the pattern on the left reads source.name and declares name. In const view = { name };, the object literal on the right creates an object: { name } is short for { name: name }. It uses the variable’s current value; later reassigning the variable does not update the property.

In const { name: displayName } = source;, name is the source key and displayName is the new variable. In a pattern, { [key]: selected } computes the property key from key. To assign to an existing variable, use ({ name: displayName } = source);. The parentheses enclose the entire standalone assignment so its opening brace is not parsed as the start of a block.

In { theme = "light" }, the default is evaluated only if the property lookup returns undefined, for instance if the property is absent or explicitly set to undefined. null does not trigger the default. Destructuring null or undefined itself throws a TypeError, even with an empty pattern.

An explicitly selected property can be found on the prototype chain. In contrast, ...rest makes a shallow copy of only the remaining own enumerable properties into a new object, including properties with Symbol keys. It must come last in the pattern, with no trailing comma.

This is ECMAScript 2024 language syntax, not a DOM feature. Runtime support varies; check object rest support in particular when targeting older runtimes.

Examples

{
  const source = { name: "Ada", theme: undefined, note: null, active: true };
  const { name: displayName, theme = "light", note = "none", ...rest } = source;

  let active;
  ({ active } = rest);

  const view = { displayName, theme, note, active };
  console.log(JSON.stringify(view));
}

Result

{"displayName":"Ada","theme":"light","note":null,"active":true}

`name` is read into `displayName`, `theme` defaults to `"light"`, and `note` stays `null`. Only `active` remains in `rest`; a separate assignment reads it before property shorthand builds `view`.

Related lessons

  • JavaScript · Lesson 31 · Advanced · Version: 4

Sources