I used to write const name = user.name; const age = user.age; four lines in a row and call it readable. Then I started reading other people’s code and noticed that every function signature I admired had braces in the parameter list. That is destructuring, and it has been in the language since ES2015. The part most tutorials skip is how it fails.

es6 destructuring

Quick answer

Destructuring assignment unpacks values from arrays (by position) or properties from objects (by name) into variables, in one statement. Four rules cover most of the surprises:

  • A default value kicks in only when the value is undefined. null passes straight through.
  • Destructuring null or undefined throws a TypeError.
  • The rest pattern (...rest) makes a shallow copy. Nested objects are shared, not cloned.
  • Array destructuring works on any iterable, not just arrays. Object destructuring works on anything that is not null or undefined.

Everything below was run on Node 24.

Access object properties and array items

javascript
const colors = ['red', 'blue'];
const [firstColor = 'white', secondColor = 'black'] = colors;
console.log(firstColor, secondColor); // => red blue

const [, , thirdColor = 'black'] = colors;
console.log(thirdColor); // => black

Array destructuring goes by position, and the empty slots between commas skip items. If nothing exists at that index, the default is used, as with thirdColor above. (The first version of this post had secondColor = black without quotes. That is a ReferenceError the moment the default is needed. Quote your string defaults.)

javascript
const obj = { bar: 'bar' };
const { foo = 'defaultFoo', bar: newBar } = obj;
console.log(foo, newBar); // => defaultFoo bar

Objects are where I use it most. foo gets its default because obj has no such property, and bar is pulled out and renamed to newBar. The same works in parameters:

javascript
const f1 = ({ foo = 'defaultFoo', bar }) => {
  console.log(foo, bar); // => defaultFoo bar
};
f1({ bar: 'bar' });

const f2 = ([foo = 'defaultFoo', bar]) => {
  console.log(foo, bar); // => defaultFoo bar
};
f2([, 'bar']);

Defaults only fire on undefined

javascript
const { n = 5 } = { n: null };
console.log(n); // => null

This one bites with API responses, where a missing field and an explicit null look the same to a human and different to the engine. If you want null to fall back too, use ?? after destructuring: const count = data.count ?? 0.

Destructuring null or undefined throws

javascript
const { a } = undefined;
// TypeError: Cannot destructure property 'a' of 'undefined' as it is undefined.

The classic cause is a function with a destructured parameter that somebody calls with no argument. Give the whole parameter a default:

javascript
function connect({ host = 'localhost', port = 5432 } = {}) {
  return `${host}:${port}`;
}

connect();               // => localhost:5432
connect({ port: 6543 }); // => localhost:6543

Nested patterns need the same care. const { a: { b } = {} } = {} gives b as undefined instead of throwing. For deep, uncertain data I now reach for optional chaining (data?.a?.b) rather than stacking defaults inside a pattern.

Computed keys and statement-level assignment

javascript
const key = 'id';
const { [key]: value } = { id: 9 };
console.log(value); // => 9

let x, y;
({ x, y } = { x: 1, y: 2 }); // parentheses are required

Without the parentheses, a { at the start of a statement is parsed as a block, and you get a syntax error.

Arrays are really iterables

Array destructuring calls the iterator protocol, so it works on a Set, a Map, a string or a generator:

javascript
const [p, q] = new Set([1, 2]);        // p = 1, q = 2
const [first, ...others] = 'héllo';    // first = 'h', others = ['é', 'l', 'l', 'o']
const [k] = {};                        // TypeError: {} is not iterable

The most useful everyday case is awaiting several things at once:

javascript
const [user, orders] = await Promise.all([fetchUser(id), fetchOrders(id)]);

And looping over entries without touching [0] and [1]:

javascript
for (const [name, score] of Object.entries(scores)) {
  console.log(name, score);
}

Create a shallow copy of objects

The rest pattern collects whatever is left:

javascript
const numbers = [1, 2, 3];
const [, ...restNumbers] = numbers;

restNumbers; // => [2, 3]
numbers;     // => [1, 2, 3]

For objects I use it to drop a property without mutating the original, for instance stripping a password before a user object goes back from an API:

javascript
const user = { name: 'User X', age: 25, password: 'xyz' };
const { password, ...newUser } = user;

newUser; // => { name: 'User X', age: 25 }

Object rest was standardised later than array destructuring, in ES2018, so very old runtimes will not have it. Two caveats I learnt the slow way:

  • It copies only own enumerable properties. Anything inherited through the prototype chain is left behind.
  • It is shallow. const { ...copy } = user gives a new top-level object, but copy.address === user.address is still true. If you need a real clone, use structuredClone(user).

Linters will also complain that password is unused. Most ESLint setups have an ignoreRestSiblings option for exactly this pattern.

Swap values

javascript
let a = 1;
let b = 2;

[a, b] = [b, a];
console.log(a, b); // => 2 1

const c = [1, 2, 3, 4];
[c[0], c[2]] = [c[2], c[0]]; // swap index 0 and 2
console.log(c); // => [ 3, 2, 1, 4 ]

If you write without semicolons, put one before a line that starts with [. Otherwise the parser reads it as an index into the previous line and you get a baffling error. A leading ;[a, b] = [b, a] is the usual fix.

Pick a subset of an object’s properties

The version of this section I published in 2020 used a comma-operator trick copied from Stack Overflow, ({a,c} = object, {a,c}). Don’t use it. It assigns to undeclared variables a and c, which throws in strict mode and in ES modules, and it leaks globals everywhere else. The surviving approach is an immediately invoked arrow function:

javascript
const obj = { a: 1, b: 2, c: 3 };
const subset = (({ a, c }) => ({ a, c }))(obj);

console.log(subset); // => { a: 1, c: 3 }

It is neat for a fixed list of keys. When the keys are dynamic, Object.fromEntries is easier to read:

javascript
const keys = ['a', 'c'];
const picked = Object.fromEntries(keys.map((k) => [k, obj[k]]));
// => { a: 1, c: 3 }

The same trick converts an array to an object:

javascript
const arr = ['a', 'b', 'c'];
const asObject = (([a, b, c]) => ({ a, b, c }))(arr);

console.log(asObject); // => { a: 'a', b: 'b', c: 'c' }

Read length, name and other properties

Object destructuring works on anything that is not null or undefined, including arrays, strings and functions. That means you can read their properties directly:

javascript
const arr = [1, 2, 3, 4, 5];
const { length } = arr;
console.log(length); // => 5

function dummyFunc(a, b, c) {
  return 'A B and C';
}

const { name, length: funcLen } = dummyFunc;
console.log(name, funcLen); // => dummyFunc 3

Newer built-ins fit in too. Object.groupBy (ES2024, available in current Node and evergreen browsers) returns an object keyed by group, so you can pull the groups straight out:

javascript
const { odd, even } = Object.groupBy([1, 2, 3, 4], (n) => (n % 2 ? 'odd' : 'even'));
console.log(odd, even); // => [ 1, 3 ] [ 2, 4 ]

If a group may be absent, remember that odd and even will be undefined, so give them defaults.

Destructuring in TypeScript

Types go after the whole pattern, not inside it. const { a: number } = obj renames a to number; it does not annotate anything. This trips up almost everyone once.

typescript
function area({ width, height }: { width: number; height: number }) {
  return width * height;
}

For anything beyond two properties, I name the type with an interface and use it in the signature.

Frequently Asked Questions

Does destructuring copy or reference the values? Primitives are copied. Objects and arrays are copied by reference, so changing a nested object through the new variable changes the original too.

Why do I get “Cannot destructure property of undefined”? The value on the right-hand side is undefined or null, often an argument nobody passed. Add = {} as a default for the parameter, or check the value first.

Can I destructure and rename at the same time? Yes. const { bar: newBar } = obj reads bar and creates a variable called newBar. Add a default with { bar: newBar = 'x' }.

Is destructuring slower than plain property access? In everyday code I have never been able to measure a difference that mattered. I would only look at it inside a hot loop, and then with a profiler, not a guess.

Does it work in all browsers? Array and object destructuring are supported everywhere modern. Object rest and spread need ES2018, which every current browser and Node release has.

The best long-form treatment is still the Destructuring chapter in Exploring ES6 by Dr Axel Rauschmayer. For the exact grammar, see MDN. If you spot a mistake or have a trap of your own to add, tell me on X @manisuec.