Skip to content
Tutorials Center
My learning

Topics

Lesson 43 of 156 ยท Objects

Destructuring

Unpack values from objects and arrays into variables with destructuring. Learn defaults, renaming, nested patterns, swapping and destructured parameters.

Code often pulls several values out of one object: a user's name, email and role, or the width and height of a box. Writing const name = user.name; line after line works, but it is repetitive. Destructuring lets you describe the shape you want and unpack everything in one statement.

The syntax mirrors the literals you already know. { } on the left of = unpacks an object, [ ] unpacks an array. It works in variable declarations, in assignments, in function parameters and in loops, and once you get used to it you will see it in almost every modern codebase.

Object destructuring

Put curly braces on the left side of a declaration and list the property names you want. Each name becomes a variable holding the property with the same name:

JS Unpacking an object

Press Run (or Ctrl + Enter) to see the console output here.

No output.

A few things to notice:

  • The order does not matter. JavaScript matches by name, not position.
  • You don't have to take every property. Unlisted ones are simply ignored.
  • A missing property doesn't throw. The variable is just undefined, exactly like reading book.publisher would be.

The object itself is untouched. Destructuring only reads from it.

Renaming

Sometimes the property name is a poor variable name, or it clashes with a variable you already have. Write property: newName to unpack into a different name:

JavaScript
const response = { status: 200, data: ["a", "b"] };

const { status: code, data: items } = response;
console.log(code);  // 200
console.log(items); // ["a", "b"]
// "status" and "data" are NOT variables here

Read the colon as "goes into": status goes into code. This is easy to mix up with object literals, where the colon means "has the value". In a pattern, the left side is always the source property and the right side is the target.

Default values

Add = value to supply a fallback when the property is missing:

JS Defaults and renaming together

Press Run (or Ctrl + Enter) to see the console output here.

No output.

A default is used only when the value is undefined, either because the property is missing or because it holds undefined. null, 0, "" and false are kept as they are. That matches how default parameters behave. If you also want to replace null, use the nullish coalescing operator after unpacking.

Array destructuring

Arrays are unpacked by position, so you use square brackets and the variables are filled from left to right:

JS Unpacking an array

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The names are up to you, because nothing is matched by name. Leave a gap between commas to skip an item. Array patterns work on anything iterable: strings, Sets, Maps and more.

Swapping variables

Array destructuring gives you a neat one-line swap, with no temporary variable:

JavaScript
let left = "cat";
let right = "dog";

[left, right] = [right, left];
console.log(left, right); // "dog" "cat"

The right side builds a new array ["dog", "cat"], and the left side unpacks it back into the two variables.

Watch for a missing semicolon. A line that starts with [ can be glued onto the line before it. If the previous line has no semicolon, doSomething()\n[a, b] = [b, a] is read as doSomething()[a, b] = โ€ฆ. This is one of the automatic semicolon insertion traps, so end the previous statement with a semicolon.

Nested patterns

Patterns can nest to match nested data. Mirror the structure of the object, and only the innermost names become variables:

JS Reaching into nested data

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Nesting is powerful, but readability drops fast. Two levels is usually the limit. Past that, unpack in steps or use optional chaining.

Nested patterns also have a trap. If an intermediate object is missing, unpacking into it throws, because you can't read a property of undefined:

JavaScript
const { customer: { name } } = {};
// TypeError: Cannot read properties of undefined (reading 'name')

Give the intermediate level a default of {} to protect against that: const { customer: { name } = {} } = data;.

Destructuring in function parameters

This is where destructuring really pays off. A function that takes an options object can unpack it right in the parameter list, so the signature shows exactly which options it understands:

JS Destructured parameters

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The trailing = {} is important. Without it, calling createButton() with no argument would try to destructure undefined and throw a TypeError. With it, the whole parameter defaults to an empty object, and then each property default kicks in.

Named options have real advantages over a long list of positional parameters. Callers can pass them in any order, skip the ones they don't need, and the call site documents itself: createButton({ label: "Delete", disabled: true }) is much clearer than createButton("Delete", "medium", true).

Destructuring in loops

for...of loops accept a pattern too. Combined with Object.entries() from Working with Objects, this is the cleanest way to walk through an object's keys and values:

JavaScript
const stock = { apples: 12, pears: 0, plums: 7 };

for (const [fruit, count] of Object.entries(stock)) {
  console.log(`${fruit}: ${count}`);
}

Object.entries() returns pairs like ["apples", 12], and [fruit, count] unpacks each pair. The same trick works with a Map, whose entries are also pairs.

Assigning to existing variables

So far every pattern has been a declaration with const or let. You can also destructure into variables that already exist. For arrays, just leave out the keyword. For objects, there is a catch: a line that starts with { is read as a code block, so you must wrap the whole assignment in parentheses:

JavaScript
let width, height;

({ width, height } = { width: 640, height: 480 });
console.log(width, height); // 640 480

The targets don't even have to be plain variables. Any assignable spot works, such as an object property: ({ x: point.x, y: point.y } = coords);. You will rarely need this, but it helps to recognize it.

Gathering the rest

A pattern can end with ...name to collect everything that wasn't unpacked: the remaining items of an array or the remaining properties of an object.

JavaScript
const [head, ...tail] = [1, 2, 3, 4];
console.log(tail); // [2, 3, 4]

const { password, ...safeUser } = { name: "Ola", password: "hunter2" };
console.log(safeUser); // { name: "Ola" }

The three dots have a second job, called spread, and the next lesson covers both in detail.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does const { size: s = 10 } = { size: null }; set s to?

    Defaults apply only when the value is undefined. null is a real value, so s becomes null.
  2. 2. After const { title: heading } = post;, which variable exists?

    In a pattern, title: heading means "read title, store it in heading". No title variable is created.
  3. 3. What is b after const [a, , b] = ["x", "y", "z"];?

    The empty slot between the commas skips the second item, so b gets the third one.
  4. 4. Why does function f({ a } = {}) {} include = {}?

    Without it, calling f() would try to destructure undefined, which throws. The default gives the pattern an empty object to read from.
  5. 5. Which line correctly destructures into two existing let variables?

    A statement that starts with { is parsed as a block, so the assignment needs parentheses. The third option tries to redeclare the variables.

Summary

  • const { a, b } = obj unpacks properties by name; const [x, y] = arr unpacks items by position.
  • Rename with prop: newName and add fallbacks with = value; defaults apply only to undefined.
  • Skip array items with empty slots, and swap variables with [a, b] = [b, a].
  • Patterns can nest, but keep them shallow and guard missing levels with = {}.
  • Destructured parameters give functions readable named options; add = {} so they can be called with no argument.
  • ...rest at the end of a pattern collects whatever is left.

Next: Spread and Rest โ€” copying, merging and collecting values with three dots.