Skip to content
jshacks.dev
Fundamentals

Destructuring Objects and Arrays in JavaScript With Examples

Destructuring unpacks arrays by position and objects by key into variables. See defaults, renaming, nesting, rest, function parameters and the null error.

8 min read
Summarize in AI
Flat illustration of an editor window full of code, with the JavaScript, npm, Node.js and Vite logos.

Almost every modern JavaScript file starts with destructuring. const { data, error } = await fetchUser(id), const [first, ...others] = items, function connect({ host, port = 5432 }). It saves a repeated result. prefix, documents which fields a function uses, and replaces a temporary variable in a swap. Its rules are few, and the mistakes people make come from three places: defaults that skip null, nested patterns that throw on a missing parent, and the syntax for assigning to existing variables. This post goes through arrays and objects, then defaults, renaming, nesting, rest, parameters and the errors. Examples run on Node.js 24. The related syntax with three dots is in the post on spread and rest, and the null and undefined rules in the post on the two empty values.

Arrays: by position

An array pattern assigns by position and works with any iterable, including strings, sets and generators.

JavaScript
const rgb = [255, 128, 0];
const [red, green, blue] = rgb;

console.log(red, green, blue);

const [first, , third] = ["a", "b", "c"];
console.log(first, third);

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

const [x, y] = new Set(["set-a", "set-b", "set-c"]);
console.log(x, y);

const [char1, char2] = "hi";
console.log(char1, char2);

let a = 1;
let b = 2;
[a, b] = [b, a];
console.log(a, b);
Text
255 128 0
a c
1 [ 2, 3, 4 ]
set-a set-b
h i
2 1

A skipped position is written as an empty slot between commas. The rest element collected the remaining items into a new array. A set and a string both worked, because the pattern uses the iteration protocol, not the array type. The last block swaps two variables with no temporary, which is the most common use of assigning to existing variables.

Objects: by name

An object pattern matches property names, and the order in the pattern does not matter.

JavaScript
const user = { id: 7, name: "Ada", role: "admin", address: { city: "London" } };

const { name, id } = user;
console.log(id, name);

const { role: userRole, missing } = user;
console.log(userRole, missing);

const { address: { city } } = user;
console.log(city);

const { id: userId, ...profile } = user;
console.log(userId, profile);
Text
7 Ada
admin undefined
London
7 { name: 'Ada', role: 'admin', address: { city: 'London' } }

role: userRole reads the role property and stores it in a variable named userRole: the name before the colon is the property, and the one after is the variable. A property that does not exist gives undefined and no error. The nested pattern reached address.city, without creating a variable named address. The rest pattern collected every property that was not named into a new object, which is the idiom for omitting a key.

Defaults apply only to undefined

A default value is used when the matched value is undefined, and not for null or any other falsy value.

JavaScript
const { port = 3000, host = "localhost", retries = 3, debug = false } = {
  port: 0,
  host: null,
  debug: undefined,
};

console.log(port, host, retries, debug);

const [one = "x", two = "y"] = ["a"];
console.log(one, two);

const { a = 1, b = a + 1 } = {};
console.log(a, b);
Text
0 null 3 false
a y
1 2

A port of 0 survived, because it is not undefined. The host stayed null, which is a frequent surprise when data comes from JSON or a database: the default is skipped and the null flows on. If null should also fall back, destructure first and then apply ??. A default can refer to earlier names in the same pattern, as b = a + 1 does, and it is evaluated only when needed.

Function parameters

Destructuring in a parameter list turns a long list of positional arguments into named options, and documents the fields the function reads.

JavaScript
function connect({ host = "localhost", port = 5432, ssl = false } = {}) {
  return `${ssl ? "tls" : "tcp"}://${host}:${port}`;
}

console.log(connect());
console.log(connect({ port: 6432 }));
console.log(connect({ host: "db.example.test", ssl: true }));

const pairs = [
  ["a", 1],
  ["b", 2],
];

for (const [key, value] of pairs) {
  console.log(key, value);
}

console.log(Object.entries({ x: 1, y: 2 }).map(([k, v]) => k + v));
Text
tcp://localhost:5432
tcp://localhost:6432
tls://db.example.test:5432
a 1
b 2
[ 'x1', 'y2' ]

The = {} after the pattern is the default for the whole argument, so calling connect() with no argument does not throw. Without it, destructuring undefined is an error, as shown next. Loops over entries are the other everyday use: for (const [key, value] of ...) and the callback parameter in map.

Destructuring null throws

The one thing a pattern cannot do is take apart null or undefined.

JavaScript
function describe({ name }) {
  return name;
}

for (const input of [undefined, null]) {
  try {
    describe(input);
  } catch (error) {
    console.log(error.name + ": " + error.message);
  }
}

try {
  const { address: { city } } = { address: null };
} catch (error) {
  console.log(error.name + ": " + error.message);
}

const { address: { city = "unknown" } = {} } = {};
console.log(city);
Text
TypeError: Cannot destructure property 'name' of 'undefined' as it is undefined.
TypeError: Cannot destructure property 'name' of 'object null' as it is null.
TypeError: Cannot read properties of null (reading 'city')
unknown

The messages name the failed property, which helps. A nested pattern fails when the parent is null, because a default only covers undefined. The last line shows the defense for an optional parent: a default of {} on the nested pattern, so a missing address becomes an empty object that the inner pattern can read. For data you do not control, optional chaining reads more clearly, as described in the post on ?..

Assigning to existing variables

Without const, let or var, an object pattern at the start of a statement is parsed as a block, so it needs parentheses.

JavaScript
let name;
let age;

({ name, age } = { name: "Grace", age: 85 });
console.log(name, age);

const target = {};
({ a: target.first, b: target.second } = { a: 1, b: 2 });
console.log(target);

try {
  eval("{ name, age } = { name: 'x', age: 1 };");
} catch (error) {
  console.log(error.name);
}
Text
Grace 85
{ first: 1, second: 2 }
SyntaxError

The parenthesized form works, and the targets can be properties, as the target example shows, which makes destructuring a way to copy selected fields between objects. The unparenthesized version is a syntax error because the opening brace starts a block statement. Array patterns do not have this problem.

Computed keys, iterables and return values

A pattern can use a computed key to read a property named by a variable, and a function can return an array or object to give several results, which the caller unpacks.

JavaScript
const field = "title";
const { [field]: value } = { title: "Destructuring" };
console.log(value);

function minMax(numbers) {
  return [Math.min(...numbers), Math.max(...numbers)];
}

const [low, high] = minMax([4, 9, 2, 7]);
console.log(low, high);

function parse(text) {
  const [key, ...rest] = text.split("=");
  return { key: key.trim(), value: rest.join("=").trim() };
}

const { key, value: parsed } = parse("url = https://example.test/?a=1");
console.log(key, parsed);

const map = new Map([["a", 1], ["b", 2]]);
const [[firstKey, firstValue]] = map;
console.log(firstKey, firstValue);
Text
Destructuring
2 9
url https://example.test/?a=1
a 1

Returning an array suits a short, positional pair that callers rename freely, as useState does in React. Returning an object suits results with named parts, so callers pick the ones they need, in any order, and the function can add a field later without breaking them. We prefer the object form beyond two values.

A worked example: normalizing an API response

Responses from outside your code arrive with optional parts, extra fields and the occasional null. A destructuring pattern at the top of the mapping function states which fields you read and what each defaults to, so the rest of the function works with clean names.

JavaScript
function toTicket({ id, title, assignee: { name: owner = "unassigned" } = {}, labels = [], ...extra }) {
  const [primary = "none", ...others] = labels;
  return { id, title, owner, primary, others, extraKeys: Object.keys(extra) };
}

console.log(
  toTicket({ id: 1, title: "Login bug", assignee: { name: "Ada" }, labels: ["bug", "p1", "web"], votes: 4 }),
);
console.log(toTicket({ id: 2, title: "Typo" }));
Text
{
  id: 1,
  title: 'Login bug',
  owner: 'Ada',
  primary: 'bug',
  others: [ 'p1', 'web' ],
  extraKeys: [ 'votes' ]
}
{
  id: 2,
  title: 'Typo',
  owner: 'unassigned',
  primary: 'none',
  others: [],
  extraKeys: []
}

The first call filled every field. The second had no assignee and no labels, and both defaults applied, with owner falling back to "unassigned" and primary to "none". The ...extra collected unknown fields so the function can report them without listing them. One warning: this version still throws if assignee is null, because the default only covers undefined. If the API can send null, destructure the assignee separately and apply ??, or validate with a schema before mapping.

The benefit of the pattern is documentation. A reader sees the shape the function depends on in the signature and does not have to scan the body for response.assignee?.name. The cost is that the signature grows, and past four or five fields it is better to give the pattern a named type in TypeScript and keep the function short.

Common review comments

Three comments come up in reviews of destructuring. First, an unused binding: a pattern that names a field it never reads, which a lint rule flags and which usually means a leftover from an edit. Second, a pattern in a loop header that allocates on each iteration, which matters only in hot paths. Third, a default that hides a bug: const { userId = 0 } = session quietly turns a missing session id into the id of a real user. When a field is required, do not give it a default.

Where destructuring stops being clearer

A pattern with three levels of nesting, several renames and defaults is harder to read than the assignments it replaces. Break it up or use a helper. Destructuring in a hot loop allocates for the rest pattern, so for performance-sensitive code, read the properties directly. And avoid destructuring for a single field you use once, where result.data reads fine.

If a variable name would shadow another in scope, rename in the pattern, as { name: userName }, and keep the more specific name. The post on scope explains the shadowing rules.

The syntax is defined in the specification under destructuring assignment and binding patterns, and MDN's page on destructuring shows more forms.

Also inFunctions
Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.