Skip to content
Velloreth
Programming 9 min read

JavaScript Destructuring: A Practical Guide

Destructuring pulls values out of arrays and objects into variables. Learn the syntax, defaults, renaming, and the nested patterns.

By

Object destructuring

Extracts values by property name.

const user = { name: 'Ada', age: 36, role: 'admin' };

const { name, age } = user;
// name = 'Ada', age = 36

The variable names must match the property names, unless you rename.

Renaming

const { name: userName, age: userAge } = user;
// userName = 'Ada', userAge = 36

This is useful when the property name collides with an existing variable, or when you want a clearer local name.

Defaults

const { port = 3000, host = 'localhost' } = config;

The default applies only when the value is undefined.

const { a = 1 } = { a: null };  // a = null — null is not undefined
const { b = 1 } = { b: 0 };     // b = 0
const { c = 1 } = { c: '' };    // c = ''
const { d = 1 } = {};           // d = 1

This trips people up constantly. If you need to treat null as missing, use ??:

const port = config.port ?? 3000;

Renaming with a default

const { name: userName = 'Anonymous' } = user;

The order is: property name, colon, new variable name, equals, default.

Array destructuring

Extracts values by position.

const [first, second] = [10, 20, 30];
// first = 10, second = 20

Skipping elements

const [, , third] = [10, 20, 30];
// third = 30

Defaults

const [a = 1, b = 2] = [10];
// a = 10, b = 2

Swapping

let a = 1, b = 2;
[a, b] = [b, a];
// a = 2, b = 1

No temporary variable needed. This is the idiomatic swap.

Rest

const [head, ...tail] = [1, 2, 3, 4];
// head = 1, tail = [2, 3, 4]

The rest pattern in objects

const { id, ...rest } = user;
// id = the id, rest = everything else

This is the standard way to omit a property, and it is common in React and in immutable updates.

// Update one property without mutating
const updated = { ...user, name: 'Grace' };

Note that rest is a shallow copy, so nested objects are shared.

Function parameters

Destructuring in parameters is the cleanest way to accept an options object.

function connect({ host = 'localhost', port = 3000, secure = false } = {}) {
  // ...
}

connect({ port: 8080 });
connect(); // works because of the = {} default

The = {} at the end is important. Without it, calling connect() with no arguments throws, because you cannot destructure undefined.

// Throws: Cannot destructure property 'host' of undefined
function connect({ host = 'localhost' }) { }
connect();

Array parameters

function distance([x1, y1], [x2, y2]) {
  return Math.hypot(x2 - x1, y2 - y1);
}

distance([0, 0], [3, 4]); // 5

Nested destructuring

const user = {
  name: 'Ada',
  address: {
    city: 'London',
    coords: { lat: 51.5, lng: -0.1 },
  },
};

const { address: { city, coords: { lat } } } = user;
// city = 'London', lat = 51.5

This works, but it becomes hard to read quickly. Note that address itself is not bound — only the nested values are.

If you need both, destructure in steps:

const { address } = user;
const { city, coords } = address;
const { lat, lng } = coords;

Three lines, but each is obvious. For deeply nested data, the stepwise version is usually better.

Destructuring in loops

for (const [index, value] of arr.entries()) {
  console.log(index, value);
}

for (const { name, email } of users) {
  sendEmail(email, name);
}

This is much cleaner than indexing into the element.

Destructuring with dynamic keys

You cannot use a variable as a destructuring key directly, but you can compute it.

const key = 'name';
const { [key]: value } = user;
// value = 'Ada'

This is occasionally useful for generic functions.

Common patterns

Extracting from a function result

const [data, error] = await fetchData();

React props

function Button({ label, onClick, variant = 'primary' }) {
  return <button onClick={onClick}>{label}</button>;
}

Import destructuring

import { useState, useEffect } from 'react';

This is the same syntax applied to module exports.

Reading from a Map

for (const [key, value] of map) {
  // ...
}

Getting the first element

const [first] = items;

Ignoring a value

const [, second] = pair;

Gotchas

Defaults only apply to undefined. null, 0, '', and false all pass through.

Destructuring undefined throws. Guard with a default or a fallback.

const { a } = undefined; // TypeError
const { a } = obj ?? {}; // safe

Nested destructuring does not bind the parent. const { address: { city } } = user binds city but not address.

The rest element must be last. const [...rest, last] = arr is a syntax error.

Object destructuring needs parentheses when it is a statement.

// Syntax error: the braces are parsed as a block
{ a, b } = obj;

// Correct
({ a, b } = obj);

This only matters when destructuring into existing variables without a declaration.

Array destructuring works on any iterable. Strings, Maps, and Sets all work.

const [firstChar] = 'hello'; // 'h'
const [firstEntry] = new Map([['a', 1]]); // ['a', 1]

Destructuring in practice

A few patterns come up constantly, and recognising them speeds up reading unfamiliar code.

Extracting a subset of props. This is the standard way to pass a subset of an object to a function or component.

const { id, name, email } = user;
sendWelcome({ name, email });

Omitting a field. The rest pattern is the idiomatic way to drop a property.

const { password, ...publicUser } = user;

Providing defaults for optional config. Destructuring with defaults documents the expected shape and the fallback in one place.

function createServer({ port = 3000, host = 'localhost', tls = false } = {}) { }

Reading multiple return values. A function that returns an array or object is destructured at the call site.

const [value, error] = tryParse(input);
const { data, status } = await response.json();

Swapping and rotating. Array destructuring makes these one-liners.

[a, b] = [b, a];
[first, ...rest] = [rest, first]; // rotate

Destructuring and readability

Destructuring is not always clearer. Two cases where it hurts.

Deeply nested patterns. A pattern with three levels of braces is hard to parse visually.

// Hard to read
const { a: { b: { c: { d } } } } = obj;

// Clearer
const { a } = obj;
const { b } = a;
const { c } = b;
const { d } = c;

Destructuring many properties at once. A pattern with fifteen names is a wall of text. If you need that many, the object is probably doing too much, or you should pass the object itself.

// A wall
const { a, b, c, d, e, f, g, h, i, j, k, l, m, n, o } = obj;

// Clearer: pass the object
function process(config) {
  return config.a + config.b;
}

The judgement: destructure when it clarifies which values you use. Do not destructure just because you can.

Destructuring and the rest of the language

Destructuring composes with other features in ways worth knowing.

With optional chaining. You cannot destructure undefined, so combine the two when the source may be missing.

const { name } = user ?? {};

With default parameters. A destructured parameter can have a default for the whole object.

function render({ title, body } = {}) { }

With computed keys. A variable can supply the key.

const field = 'email';
const { [field]: value } = user;

With async results. Destructuring the resolved value of a promise is common.

const { data, error } = await client.get('/users');

With imports. The same syntax applies to module exports, which is why import { useState } from 'react' looks like destructuring — it is a related but distinct mechanism.

A note on API design

Destructuring shapes how you design function signatures. A function that takes an options object is easier to extend than one with positional parameters, because adding a field does not change the call sites. Destructuring in the parameter list documents which fields the function reads, and defaults document which are optional. The trade-off is that a positional signature is shorter for one or two arguments, and it enforces the order. The rule of thumb: use positional parameters for one or two obvious arguments, and an options object once there are three or more, or once any of them is optional.

Practical guidance

  • Destructure function parameters to document the expected shape.
  • Add = {} to an options parameter so it can be called with no arguments.
  • Remember defaults apply only to undefined.
  • Use renaming to avoid collisions and improve clarity.
  • Use the rest pattern to omit properties.
  • Destructure in steps when nesting goes beyond two levels.
  • Use [a, b] = [b, a] to swap.
  • Guard against undefined before destructuring.

For the related guides, see javascript-array-methods-guide and javascript-object-methods-guide. For the broader context, null-vs-undefined-vs-nil and higher-order-functions-explained.

Quotable summary

Object destructuring uses braces and matches by key name, while array destructuring uses brackets and matches by position. Defaults apply only when the value is undefined, not when it is null, 0, or an empty string, which is a frequent source of bugs. Renaming with a colon lets you destructure a property into a differently named variable, and the rest pattern collects the remaining values. Destructuring in function parameters is the cleanest way to accept an options object, and adding = {} lets the function be called with no arguments. Nested destructuring works but becomes hard to read quickly, so destructure in steps when nesting goes beyond two levels.

Frequently asked questions

What is destructuring in JavaScript?
It is syntax that extracts values from arrays or objects into variables in a single statement. Object destructuring matches by property name, and array destructuring matches by position.
How do I set a default value when destructuring?
Write the default after an equals sign: const { port = 3000 } = config. The default applies only when the value is undefined, not when it is null, 0, or an empty string.
How do I rename a variable while destructuring?
Use a colon: const { name: userName } = user. The property is name, and the variable is userName.
Can I destructure function parameters?
Yes, and it is the standard way to accept an options object: function connect({ host, port = 3000 }) { }. It documents the expected shape at the call site.
How do I swap two variables?
Use array destructuring: [a, b] = [b, a]. No temporary variable is needed.
What is the rest pattern in destructuring?
It collects the remaining values: const [first, ...rest] = arr collects everything after the first element, and const { id, ...others } = obj collects all properties except id.