Q&A
How to destructure arrays and objects in JavaScript
Overview
Before destructuring, extracting multiple values meant writing multiple assignment lines. Destructuring collapses all of that into one concise statement that mirrors the shape of the data. It's used everywhere in modern JavaScript - function parameters, import statements, useState return values, and API responses.
graph TD
A[Destructuring] --> B["Array [ ] → assigns by position"]
A --> C["Object { } → assigns by property name"]
B --> D[Swap, skip, rest, defaults]
C --> E[Rename, defaults, nested, rest]
style A fill:#1e1b4b,color:#fff
Array Destructuring
Positions map left to right:
const [a, b, c] = [1, 2, 3];
// a=1, b=2, c=3
// Skip elements with empty commas:
const [first, , third] = [10, 20, 30];
// first=10, third=30
// Default values:
const [x = 0, y = 0] = [5];
// x=5, y=0 (second element missing, uses default)
// Rest element (must be last):
const [head, ...tail] = [1, 2, 3, 4];
// head=1, tail=[2,3,4]
Swap without a temp variable
let m = 1, n = 2;
[m, n] = [n, m]; // m=2, n=1
Object Destructuring
Property names match, positions don't matter:
const { name, age } = { name: "Ada", age: 30, city: "London" };
// name="Ada", age=30 (city ignored)
// Rename with colon:
const { name: fullName, age: years } = person;
// fullName="Ada", years=30 (name and age aren't declared)
// Default values:
const { role = "user" } = { name: "Ada" };
// role="user" (property missing)
// Rest object:
const { name: n, ...rest } = { name: "Ada", age: 30, city: "London" };
// n="Ada", rest={ age:30, city:"London" }
Combined: Rename + Default
const { status: httpStatus = 200 } = response;
// reads response.status, stores in httpStatus, defaults to 200
Rename and default can be combined in one clause.
Nested Destructuring
const { address: { city, zip } } = {
name: "Ada",
address: { city: "London", zip: "EC1A" }
};
// city="London", zip="EC1A"
// Nested array:
const [[a, b], [c, d]] = [[1, 2], [3, 4]];
Destructuring in Function Parameters (very common)
Avoids const { name } = opts; inside the body:
function greet({ name, greeting = "Hello" }) {
return `${greeting}, ${name}!`;
}
greet({ name: "Ada" }); // "Hello, Ada!"
// Array params:
const sum = ([a, b]) => a + b;
sum([3, 4]); // 7
Destructuring in Loops
const users = [
{ id: 1, name: "Ada" },
{ id: 2, name: "Linus" },
];
for (const { id, name } of users) {
console.log(id, name);
}
// or with entries:
for (const [index, value] of ["a", "b", "c"].entries()) {
console.log(index, value);
}
Practical Patterns
// React useState:
const [count, setCount] = useState(0);
// API response:
const { data: { users }, status } = await axios.get("/api/users");
// Module imports:
import { useState, useEffect } from "react";
Why This Matters in Interviews
Destructuring is everywhere in modern JS. Interviews check: array (positional) vs object (name-based) syntax, renaming ({ x: newName }), defaults, rest (...rest), nested patterns, and function-parameter destructuring. The swap idiom ([a, b] = [b, a]), skipping array elements, and combining rename + default are classic follow-ups. Recognizing destructuring in useState, imports, and for...of patterns shows real fluency.
Common Pitfalls
- Object destructuring syntax can look like a block
{}- use parentheses for standalone statements:({ a } = obj). - Renaming syntax is
{ original: alias }, not{ alias: original }(counter-intuitive at first). - Nested destructuring fails with a
TypeErrorif an intermediate value isnull/undefined- use optional chaining for safety. - The rest element must be last (in both array and object destructuring).
- Default values only activate for
undefined, not fornull.
References
- MDN Destructuring assignment: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment