Destructuring: arrays, objects and defaults

Destructuring takes a value apart in one declaration. The left side of the equals sign looks like the value it expects, and the names inside receive the pieces: const [first, second] = list; for an array and const { name, age } = user; for an object. The syntax reads like the data, which is the reason it replaced five lines of indexing with one line that can be checked by eye.

JavaScript allows a default for a missing piece, a new name for a property, a pattern inside a pattern, and a destructured parameter list on a function. The rest element, written with three dots, collects what is left over; it is the subject of the next lesson and appears here only where a pattern needs it.

Array patterns

An array pattern takes the elements in order. A comma with nothing before it skips an element, and the names may be declared with const, with let or assigned without a keyword when the bindings already exist, which is what makes a swap one statement.

const numbers = [1, 2, 3, 4, 5]; const [first, second, ...rest] = numbers; console.log(first, second, rest); const [, , third] = numbers; console.log('third:', third); let a = 1; let b = 2; [a, b] = [b, a]; console.log('swapped:', a, b);

node arrays.mjs

1 2 [ 3, 4, 5 ]
third: 3
swapped: 2 1

The first line prints the array that the rest element built, in the format console.log uses for an array. The second line reaches the third element through two empty slots, and the last line swapped two let bindings without a temporary variable: the right side is built first, then the names are assigned from it.

Object patterns

An object pattern takes the properties by name, so the order does not matter and a missing property is undefined. A colon renames the binding: { name: userName } reads the property name into a binding called userName. An equals sign after the name supplies a default for the case where the property is missing or undefined.

const user = { name: 'Ada', age: 36, city: 'London' }; const { name, age } = user; console.log(name, age); const { name: userName, city: town } = user; console.log(userName, 'lives in', town); const { country = 'unknown', zip } = user; console.log('country:', country); console.log('zip:', zip); const { name: firstName, ...others } = user; console.log('firstName:', firstName); console.log('others:', Object.keys(others).join(', '));

node objects.mjs

Ada 36
Ada lives in London
country: unknown
zip: undefined
firstName: Ada
others: age, city

The default filled in for the property that does not exist, and a property without a default printed undefined instead of throwing. The rest element in the last pattern collected the properties that were not named, which is a common way to drop one field from an object before it is sent somewhere.

Nested patterns

A pattern may hold another pattern wherever a value is expected. The left side of the program below follows the shape of the object: customer holds an object, address inside it holds another, and items is an array whose first element is an object. Both names are taken in one declaration.

const order = { id: 42, customer: { name: 'Ada', address: { city: 'London', zip: 'N1' } }, items: [ { sku: 'A1', qty: 2 }, { sku: 'B2', qty: 1 }, ], }; const { customer: { name, address: { city }, }, items: [firstItem], } = order; console.log(name, city); console.log('first item:', firstItem.sku, firstItem.qty);

node nested.mjs

Ada London
first item: A1 2

customer and address are only steps on the way down; the bindings are name and city. The array pattern at the end names the first item and ignores the rest, which is clearer than order.items[0] repeated on three lines. A missing step throws a TypeError, so a nested pattern is a promise that the shape is there.

Destructured parameters

A parameter may be a pattern, which turns a function that takes an object into a function with named and defaulted inputs. The first function below takes an object and an array, and the second supplies a default for the whole object as well, so a call with no argument still works. The two defaults are different things: one fills a missing property, the other replaces a missing argument.

function describe({ name, role = 'reader' }, [first, second = 'none']) { return `${name} (${role}), first: ${first}, second: ${second}`; } console.log(describe({ name: 'Ada' }, ['math'])); function connect({ host = 'localhost', port = 8080 } = {}) { return `${host}:${port}`; } console.log(connect()); console.log(connect({ port: 3000 }));

node params.mjs

Ada (reader), first: math, second: none
localhost:8080
localhost:3000

The call with one element in the array left second at its default, and the call with no argument at all reached the empty object of the parameter and then the two property defaults. Without the = {} the call connect() would throw, because the pattern would try to read a property of undefined.

Exercises

  1. Destructure the last two elements of the array in arrays.mjs in one pattern, without naming the first three. Which index does the first name receive?
  2. Give city a default in objects.mjs, then delete the property from the object and run it again. Which line changes?
  3. Take zip out of the nested pattern in nested.mjs and print it. What is the value, and why is there no error?
  4. Call describe with an array of three elements and no second name. Which defaults apply?
  5. Remove the = {} from connect and call it with no argument. Which error arrives, and which line of the message names the cause?

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. What does const [a, b] = [1, 2, 3]; bind?

    Answer

    a is 1 and b is 2

    An array pattern takes the elements in order and ignores the ones that are not named.

  2. What does this program print? const user = { name: "Ada", age: 36 }; const { name: userName } = user; console.log(userName);

    Answer

    Ada

    The colon renames the binding, so the property name is read into a variable called userName.

  3. What does this program print? const { role = "reader" } = { name: "Ada" }; console.log(role);

    Answer

    reader

    The property is missing, so the default value fills the binding.

  4. What does this program print? const order = { customer: { city: "London" } }; const { customer: { city } } = order; console.log(city);

    Answer

    London

    The nested pattern walks into customer and binds the city property of the inner object.

  5. What does a hole in an array pattern do, as in const [, second] = list;?

    Answer

    It skips the element at that position

    Each comma moves to the next element, so a comma with no name leaves that element unbound.

  6. What does this program print? let a = 1; let b = 2; [a, b] = [b, a]; console.log(a, b);

    Answer

    2 1

    The right side is built before the assignment, so the two names exchange their values.

  7. What does function connect({ port = 8080 } = {}) do for the call connect()?

    Answer

    It uses the empty object default and then the port default

    The parameter default supplies the empty object and the property default then fills the port.

  8. Which property does const { name: firstName, ...others } = user; leave out of others?

    Answer

    name

    The named property goes to firstName, and the rest element collects everything else.

  9. What happens when the path of a nested pattern does not exist?

    Answer

    A TypeError, because a property is read from undefined

    The pattern reads the next step from a value that is not an object, and that read throws.

  10. What does this program print? const { name = "nobody", city = "unknown" } = { name: "Ada" }; console.log(name, city);

    Answer

    Ada unknown

    The name property exists and wins over its default, while the missing city takes the default.

The code on this page was run with Node.js 24.22.1 and linted with ESLint 10.14.0 on Alpine Linux 3.24.3 (x86_64) in a Docker container.

Article author: Arthur Isaev