Browse topics

Destructuring assignment

Version
es2025
Since
es2015
Review
Draft

Summary#

Destructuring copies values out of objects and iterables into variables. Patterns can rename properties, skip array positions, nest and supply defaults.

Syntax#

js
const { key: newName = fallback } = object;
const [first, , third] = iterable;

Example#

js
/** @type {{ host: string, port?: number, options: { retries?: number | null } }} */
const server = { host: "localhost", options: { retries: null } };
const {
  host: name,
  port = 8080,
  options: { retries = 3 },
} = server;
console.log(name, port, retries);

let [left, right] = ["a", "b"];
[left, right] = [right, left];
console.log(left, right);

Expected output#

Text
localhost 8080 null
b a

Common mistakes#

A default applies only when the value is undefined, so null passes through. Destructuring null or undefined itself throws a TypeError, including a nested pattern whose parent property is missing.

Version applicability#

ES2015 added destructuring patterns. Rest properties in object patterns, such as const { id, ...rest } = record, arrived in ES2018.

Sources#

Attribution
DevLookup contributors
License
CC-BY-4.0