Destructuring Assignment

Published by Brayan K

Destructuring is the modern way to unpack values out of arrays and objects into their own variables — in a single, readable line. If you've ever written const name = user.name; const age = user.age; three times in a row, this lesson is about to save you a lot of typing.

Part of the free JavaScript course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.

Choose positions for arrays and property names for objects

A destructuring pattern describes which values to read and where to put them. An array pattern follows iteration order; an object pattern looks up named properties. The braces and brackets on the left are a pattern, not a request to create another copy of the source.

const dimensions = [8, 3];
const [width, height] = dimensions;
console.log(width, height);

const item = { quantity: 3, sku: "A17" };
// Property order in the pattern does not need to match the record.
const { sku, quantity } = item;
console.log(sku, quantity);

// ✅ Expected output:
// 8 3
// A17 3

Use the pattern that matches the input contract. A tuple-like pair gives positions meaning; a record gives property names meaning. Arrays and Objects owns creating and updating those containers.

const row = ["A17", "unused", 3];
const [sku, , quantity] = row;
console.log(sku);
console.log(quantity);

// ✅ Expected output:
// A17
// 3

The empty position still consumes a value. Array patterns accept iterable values rather than arbitrary objects with numeric-looking keys; Iterators & Iterables owns that protocol.

const row = { 0: "A17", 1: 3, length: 2 };
const [sku, quantity] = row;
console.log(sku, quantity);

// ✅ Expected error:
// TypeError: row is not iterable

Renaming changes the local binding, not the source property

In an object pattern, the name before the colon identifies the property to read; the name after it is the local binding. Renaming is useful when two records both have a property with the same name, or when the property name is unclear in the current function.

const item = { sku: "A17", quantity: 3 };
const { sku: itemCode, quantity: units } = item;
console.log(itemCode);
console.log(units);
console.log(item.sku);

// ✅ Expected output:
// A17
// 3
// A17
const item = { sku: "A17" };
const { sku: itemCode } = item;
console.log(itemCode);
console.log(sku);

// ✅ Expected output:
// A17

// ✅ Expected error:
// ReferenceError: sku is not defined

Read the colon as "read this property into that binding", not as a type annotation. The source still has a sku property, while this program declares itemCode. Access the original property through item.sku if that is what you intend.

Defaults replace undefined, including a missing value

A default in a destructuring pattern runs when the extracted value is undefined. It does not replace null, false, zero or an empty string. Missing array positions and missing object properties can therefore use defaults without discarding those other values.

const { quantity = 1 } = {};
const [first = "fallback", second = "fallback"] = [undefined, null];
const { count = 10, enabled = true, label = "untitled" } = {
  count: 0,
  enabled: false,
  label: ""
};
console.log(quantity);
console.log(first, second);
console.log(count, enabled, JSON.stringify(label));

// ✅ Expected output:
// 1
// fallback null
// 0 false ""
function fallback() {
  console.log("fallback evaluated");
  return 1;
}
const { quantity: present = fallback() } = { quantity: 3 };
console.log(present);
const { quantity: missing = fallback() } = {};
console.log(missing);

// ✅ Expected output:
// 3
// fallback evaluated
// 1

The fallback expression can have side effects, so its timing matters. A present null value bypasses the fallback; a separate input rule must decide whether null is allowed. Type Coercion (== vs ===) owns distinguishing absence, truthiness and explicit validation.

A default for a property does not repair a null source

Before an object pattern can read a property, its source must permit that access. A property default does not rescue destructuring from null or undefined because the failure happens before a property value is available to default.

const item = null;
const { quantity = 1 } = item;
console.log(quantity);

// ✅ Expected error:
// TypeError: Cannot read properties of null (reading 'quantity')

Decide at the input boundary whether a missing record should be rejected or replaced with an empty record. Silently replacing it is only appropriate when the application contract really permits absent data. Do not describe defaults as validation.

Nested patterns need a decision at every optional level

A nested pattern reads through the matching nested property. The outer property name is not automatically declared as a local binding. An empty-object default can handle an undefined intermediate value, but it still does not replace an explicitly null intermediate value.

const user = {};
const { preferences: { theme = "light" } = {} } = user;
console.log(theme);

// ✅ Expected output:
// light
const user = { preferences: null };
const { preferences: { theme = "light" } = {} } = user;
console.log(theme);

// ✅ Expected error:
// TypeError: Cannot read properties of null (reading 'theme')

Keep nested patterns shallow enough that their assumptions stay visible. For mixed or untrusted data, separate guards may be clearer than one dense pattern. Optional Chaining & Nullish Coalescing owns optional property access when you only need to read a value.

Destructuring reads now and preserves referenced objects

Extracting a primitive value gives the local binding that value at the time of destructuring. It does not keep the binding synchronized with future writes to the source property. An extracted object value still refers to the same object, so destructuring is not a deep clone.

const item = { quantity: 2, settings: { colour: "blue" } };
const { quantity, settings } = item;
item.quantity = 5;
settings.colour = "green";
console.log(quantity);
console.log(item.quantity);
console.log(item.settings.colour);
console.log(settings === item.settings);

// ✅ Expected output:
// 2
// 5
// green
// true

This follows ordinary value and reference rules rather than adding a special copying operation. Spread & Rest Operators owns collecting remaining values and the shallow-copy boundary of spread.

Assignment to existing bindings needs the right statement form

A declaration pattern creates bindings with const or let. An assignment pattern instead writes to bindings that already exist. At the start of a statement, wrap an object assignment pattern in parentheses so its opening brace is parsed as an expression rather than a block.

let itemCode = "pending";
const item = { sku: "A17" };
({ sku: itemCode } = item);
console.log(itemCode);

// ✅ Expected output:
// A17
let itemCode;
const item = { sku: "A17" };
{ sku: itemCode } = item;
console.log(itemCode);

// ✅ Expected error:
// SyntaxError: Unexpected token '='
let left = "blue";
let right = "green";
[left, right] = [right, left];
console.log(left, right);

// ✅ Expected output:
// green blue

The array on the right is evaluated before assignment to the left-hand bindings, which is why the swap does not overwrite a value too early. Both destinations must allow reassignment.

An options-parameter default handles an omitted argument

A function can destructure its argument directly. A default for the whole parameter handles an omitted or undefined argument, while property defaults handle missing properties within the supplied record. Neither default makes a null argument valid.

function describe({ label = "untitled", quantity = 1 } = {}) {
  return label + ": " + quantity;
}
console.log(describe());
console.log(describe({ label: "Pack" }));
console.log(describe({ label: "Pack", quantity: 0 }));

// ✅ Expected output:
// untitled: 1
// Pack: 1
// Pack: 0

This function assumes an appropriate record when an argument is supplied. Functions owns the broader parameter and return contract. Avoid hiding required input behind a default merely to prevent an exception.

Complete a renamed property and a default quantity

Read sku into the local binding itemCode and use one as the quantity when the property is missing. Fill the two blanks from the literal hints, then inspect the original record to see that its properties were not renamed or added.

const item = { sku: "A17" };
const { sku: ___, quantity = ___ } = item;
// 👉 replace ___ with itemCode
// 👉 replace ___ with 1
console.log(itemCode);
console.log(quantity);
console.log(JSON.stringify(item));

// ✅ Expected output:
// A17
// 1
// {"sku":"A17"}

Build a small order summary from optional fields

Write orderSummary with a destructured parameter. Default id to "unassigned", quantity to one, and delivery.city to "Unknown". Allow an omitted argument and an omitted delivery record. Return a new record with the keys orderId, quantity and city, then print JSON for a full order, an order with quantity zero and no delivery, and an omitted argument. The contract permits missing fields but does not accept null as a replacement record.

function orderSummary({
  id: orderId = "unassigned",
  quantity = 1,
  delivery: { city = "Unknown" } = {}
} = {}) {
  return { orderId, quantity, city };
}
console.log(JSON.stringify(orderSummary({
  id: "A17",
  quantity: 3,
  delivery: { city: "Leeds" }
})));
console.log(JSON.stringify(orderSummary({ id: "B24", quantity: 0 })));
console.log(JSON.stringify(orderSummary()));

// ✅ Expected output:
// {"orderId":"A17","quantity":3,"city":"Leeds"}
// {"orderId":"B24","quantity":0,"city":"Unknown"}
// {"orderId":"unassigned","quantity":1,"city":"Unknown"}

Each fallback has a different location and responsibility. Quantity zero is retained because it is not undefined. A null delivery record would still violate this contract; add explicit validation if the caller can supply it.

Reference: MDN documents destructuring patterns, defaults and assignment syntax.

Practice quiz

What does this complete program print? const [first, , third] = ["A", "B", "C"]; console.log(first, third);

  • A C
  • A B
  • B C
  • A undefined

Answer: A C. The empty pattern position consumes the middle value.

What does this complete program print? const { sku: code } = { sku: "A17" }; console.log(code);

  • undefined
  • A17
  • sku
  • ReferenceError: code is not defined

Answer: A17. The property name is sku and the created local binding is code.

What does this complete program print? const { quantity = 1 } = { quantity: 0 }; console.log(quantity);

  • 1
  • undefined
  • 0
  • null

Answer: 0. Defaults apply to undefined, not to zero.

What does this complete program print? const [value = "default"] = [null]; console.log(value);

  • default
  • undefined
  • TypeError: null is not iterable
  • null

Answer: null. The array is iterable and its first value is null; that value does not trigger the default.

What does this complete program print? let calls = 0; function fallback() { calls++; return 1; } const { value = fallback() } = { value: 4 }; console.log(value, calls);

  • 4 0
  • 4 1
  • 1 1
  • 1 0

Answer: 4 0. The supplied property is defined, so the default expression is not evaluated.

What does this complete program print? const source = { count: 2 }; const { count } = source; source.count = 9; console.log(count);

  • 9
  • 2
  • undefined
  • TypeError: Assignment to constant variable.

Answer: 2. The local primitive value was read during destructuring; it is not a live link to the source property.

What does this complete program print? const { options: { mode = "basic" } = {} } = {}; console.log(mode);

  • undefined
  • TypeError: Cannot read properties of undefined (reading 'mode')
  • basic
  • {}

Answer: basic. The missing options value uses an empty record, then the missing mode uses its own default.

What does this complete program print? function label({ name = "Guest" } = {}) { return name; } console.log(label());

  • undefined
  • {}
  • TypeError: Cannot read properties of undefined (reading 'name')
  • Guest

Answer: Guest. The whole-parameter default supplies an empty object, allowing the property default to run.

Continue this course

Related lessons