Destructuring
Destructuring is a concise ES6 syntax that lets you unpack values from arrays and properties from objects into individual variables in a single statement. Instead of writing multiple assignment lines, destructuring lets you extract exactly what you need — with support for default values, aliases, nested patterns, and function parameter unpacking — all in one clean expression.
undefined
Two Types of Destructuring
Destructuring works with arrays (position-based) and objects (name-based). The left-hand side of the assignment mirrors the shape of the data structure you want to unpack:
// a=1 b=2 c=3
// name=user.name age=user.age
const name = user.name;
const age = user.age;
const x = coords[0];
// NEW WAY — destructuring
const { name, age } = user; // object
const [x, y] = coords; // array
const { name: firstName } = user; // alias
const { role = "user" } = prefs; // default value
Array Destructuring
Array destructuring extracts values by position using square brackets on the left of the assignment. The variable names are yours to choose — JavaScript matches by index, not by name:
, ,
undefined if the array is
shorter
...tail to capture the
remainder
[a, b] = [b, a]
undefined
// ── Basic array destructuring ────────────────────────────────
const [x, y, z] = [10, 20, 30];
console.log(x, y, z); // 10 20 30
// ── Skip elements with empty comma ──────────────────────────
const [first, , third] = ["a", "b", "c"];
console.log(first, third); // "a" "c" (b skipped)
// ── Default values ───────────────────────────────────────────
const [p = 0, q = 0, r = 0] = [5, 10];
console.log(p, q, r); // 5 10 0 ← r defaults to 0
// ── Rest in array destructuring ──────────────────────────────
const [head, ...tail] = [1, 2, 3, 4, 5];
console.log(head); // 1
console.log(tail); // [2, 3, 4, 5]
// ── Swap two variables (classic trick) ──────────────────────
let a = 1, b = 2;
[a, b] = [b, a];
console.log(a, b); // 2 1
// ── Return multiple values from a function ───────────────────
function minMax(arr) {
return [Math.min(...arr), Math.max(...arr)];
}
const [min, max] = minMax([3, 1, 7, 2, 9]);
console.log(min, max); // 1 9
// ── Destructure from any iterable ───────────────────────────
const [c1, c2, c3] = "ABC";
console.log(c1, c2, c3); // "A" "B" "C"
const [v1, v2] = new Set([10, 20, 30]);
console.log(v1, v2); // 10 20Object Destructuring
Object destructuring extracts properties by name using curly braces on the left side. You don't have to extract every property — just list the ones you need. Variable names must match the property key unless you use aliasing:
// ── Basic object destructuring ───────────────────────────────
const user = { name: "Alice", age: 28, role: "admin" };
const { name, age, role } = user;
console.log(name, age, role); // "Alice" 28 "admin"
// ── Alias / rename during destructuring ──────────────────────
const { name: firstName, age: years } = user;
console.log(firstName); // "Alice"
console.log(years); // 28
// name and age no longer exist as variable names here
// ── Default values ───────────────────────────────────────────
const settings = { theme: "dark" };
const { theme, lang = "en", fontSize = 14 } = settings;
console.log(theme, lang, fontSize); // "dark" "en" 14
// ↑ lang and fontSize default because they're undefined in settings
// ── Alias + default combined ─────────────────────────────────
const { name: n = "Guest", score: s = 0 } = {};
console.log(n, s); // "Guest" 0
// ── Extract only what you need ───────────────────────────────
const response = {
status: 200, data: { users: [1, 2] }, headers: {}, meta: {}
};
const { status, data } = response; // ignore headers & meta
console.log(status, data); // 200 { users: [1, 2] }
// ── Rest in object destructuring ─────────────────────────────
const { name: uName, ...rest } = user;
console.log(uName); // "Alice"
console.log(rest); // { age: 28, role: "admin" }
// ── Destructure in a loop ────────────────────────────────────
const users = [
{ id: 1, name: "Alice" },
{ id: 2, name: "Bob" },
];
for (const { id, name } of users) {
console.log(`${id}: ${name}`); // 1: Alice 2: Bob
}undefined.
They do not kick in for null, 0, false,
or "". For example, const { score = 10 } = { score: 0 }
gives score = 0, not 10, because 0 is not
undefined.
Nested Destructuring
You can destructure values nested inside other objects or arrays by mirroring the shape of the data on the left side. Nest brackets inside brackets, or braces inside braces — the pattern must match the structure:
{ outer: { inner } } to reach inside
undefined, JavaScript
throws TypeError
// ── Nested object destructuring ─────────────────────────────
const company = {
name: "K2 Infocom",
address: {
city: "Surat",
state: "Gujarat",
pin: "395001",
},
ceo: { name: "Ketan", since: 2010 },
};
const {
name: companyName,
address: { city, state },
ceo: { name: ceoName, since },
} = company;
console.log(companyName); // "K2 Infocom"
console.log(city, state); // "Surat" "Gujarat"
console.log(ceoName, since); // "Ketan" 2010
// ── Nested array destructuring ──────────────────────────────
const matrix = [[1, 2], [3, 4], [5, 6]];
const [[r1c1, r1c2], [r2c1, r2c2]] = matrix;
console.log(r1c1, r1c2); // 1 2
console.log(r2c1, r2c2); // 3 4
// ── Mixed — object containing array ─────────────────────────
const student = {
name: "Alice",
scores: [92, 88, 95],
address: { city: "Surat" },
};
const {
name: stdName,
scores: [top, second],
address: { city: stdCity },
} = student;
console.log(stdName); // "Alice"
console.log(top, second); // 92 88
console.log(stdCity); // "Surat"
// ── Guard against undefined intermediate keys ───────────────
const { address: { zip } = {} } = {}; // safe — no TypeError
console.log(zip); // undefinedFunction Parameter Destructuring
One of the most practical uses of destructuring is directly in function parameters. Instead of receiving a whole object and accessing its properties inside the function body, you destructure them right in the signature — making the expected shape immediately visible:
// ── Old way — access properties inside body ──────────────────
function greetOld(user) {
console.log(`Hello, ${user.name}! You are ${user.age}.`);
}
// ── New way — destructure in the parameter ───────────────────
function greet({ name, age }) {
console.log(`Hello, ${name}! You are ${age}.`);
}
greet({ name: "Alice", age: 28 }); // Hello, Alice! You are 28.
// ── With default values in params ───────────────────────────
function createBtn({
label = "Click me",
color = "blue",
disabled = false,
size = "md",
} = {}) {
console.log(`[${size}] ${label} — ${color}${disabled ? " (off)" : ""}`);
}
createBtn({ label: "Submit", color: "green" });
// [md] Submit — green
createBtn(); // [md] Click me — blue (all defaults)
// ── React-style component (conceptual) ──────────────────────
function UserCard({ name, avatar, role = "member", isOnline = false }) {
return `<div>${name} (${role})${isOnline ? " 🟢" : " ⚫"}</div>`;
}
// ── Array param destructuring ────────────────────────────────
function sumFirst([a, b, c = 0]) {
return a + b + c;
}
console.log(sumFirst([10, 20])); // 30 (c defaults to 0)
console.log(sumFirst([1, 2, 3])); // 6
// ── Rename inside parameter destructuring ───────────────────
function display({ name: title, price: cost }) {
console.log(`${title} costs $${cost}`);
}
display({ name: "Laptop", price: 800 }); // Laptop costs $800
= {} default
= {} at the end of the
parameter so the function can be called with no arguments without
throwing a TypeError. function fn({ a } = {}) works even when called as
fn() — without = {}, calling it with no argument crashes.
Destructuring in Loops & Module Imports
Destructuring works seamlessly inside
for...of loops and with ES6 module imports —
two patterns you'll encounter constantly in real codebases:
// ── for...of with object array ───────────────────────────────
const products = [
{ name: "Laptop", price: 800, inStock: true },
{ name: "Phone", price: 400, inStock: false },
{ name: "Tablet", price: 250, inStock: true },
];
for (const { name, price, inStock } of products) {
if (inStock) console.log(`${name}: $${price}`);
}
// Laptop: $800
// Tablet: $250
// ── Object.entries with destructuring ──────────────────────
const config = { host: "localhost", port: 3000, debug: true };
for (const [key, value] of Object.entries(config)) {
console.log(`${key} = ${value}`);
}
// host = localhost
// port = 3000
// debug = true
// ── Map iteration with destructuring ────────────────────────
const scores = new Map([["Alice", 92], ["Bob", 87]]);
for (const [student, score] of scores) {
console.log(`${student}: ${score}`); // Alice: 92 Bob: 87
}
// ── Module import destructuring ──────────────────────────────
// import { useState, useEffect } from "react";
// import { Router, Route, Link } from "react-router-dom";
// ── Array method with destructuring ────────────────────────
const pairs = [[1, "one"], [2, "two"], [3, "three"]];
pairs.forEach(([num, word]) => {
console.log(`${num} = ${word}`);
}); // 1 = one 2 = two 3 = threeArray vs Object Destructuring — Full Comparison
Here's a side-by-side reference for all the destructuring features you need to know:
| Feature | Array Destructuring | Object Destructuring |
|---|---|---|
| Syntax brackets | [ ] square brackets | { } curly braces |
| Matching by | Position (index 0, 1, 2…) | Property name (key) |
| Variable naming | Any name you choose | Must match key, or use key: alias |
| Skip elements | [a, , c] — blank comma |
Just don't list the key |
| Default value | [a = 0] |
{ a = 0 } |
| Rest / remainder | [first, ...rest] | { a, ...rest } |
| Works with | Arrays, strings, Sets, any iterable | Plain objects, class instances |
| Nested | [[a, b], [c, d]] | { a: { b } } |
Real-World Use Cases
Destructuring shows up everywhere in modern JavaScript — from API responses to React hooks and module imports:
[value, setter] — array destructuring names
them on one line: const [count, setCount] = useState(0)[a, b] = [b, a]
— clean, no extra allocation needed.import { useState, useEffect } from "react" — named imports use object
destructuring semantics.
function Card({ title, img, onClick }) — for clean, self-documenting
components.
for (const [key, val] of Object.entries(obj))
const { password, ...safeUser } = user before sending to client.
Try It — Live Editor
Experiment with all forms of destructuring below. Try modifying the data or adding default values to see exactly what gets extracted.
Common Patterns & Recipes
Here are the most useful destructuring patterns you'll reach for every day in real JavaScript and modern frameworks:
// ── Pick specific fields from API response ───────────────────
async function loadUser(id) {
const { data: { name, email, avatar } } = await fetch(`/api/users/${id}`).then(r => r.json());
return { name, email, avatar };
}
// ── Parse query string to object (with defaults) ─────────────
const { page = 1, limit = 10, sort = "asc" } = queryParams;
// ── Rename conflicting variables ─────────────────────────────
const { name: userName } = user;
const { name: productName } = product; // no variable collision
// ── Destructure after await ──────────────────────────────────
const { status, data } = await fetchOrder(orderId);
// ── React useState (array destr) ─────────────────────────────
const [count, setCount] = useState(0);
const [isOpen, setIsOpen] = useState(false);
// ── Config with full defaults ────────────────────────────────
function connect({
host = "localhost",
port = 5432,
db = "mydb",
ssl = false,
} = {}) {
console.log(`${host}:${port}/${db} ssl=${ssl}`);
}
connect({ port: 3306, db: "shop" }); // localhost:3306/shop ssl=false
connect(); // localhost:5432/mydb ssl=false
// ── minMax utility (array return + destr) ────────────────────
const range = arr => [Math.min(...arr), Math.max(...arr)];
const [lo, hi] = range([3, 1, 8, 4]);
console.log(lo, hi); // 1 8c after
const [a, b, c = 99] = [1, 2]?
const { name: n } = { name: "Alice" }, which variable
holds "Alice"?- Array destructuring uses
[ ]and extracts values by position. Variable names are yours to choose. Skip with blank commas[a, , c]. - Object destructuring uses
{ }and extracts values by property name. Variables must match keys, or usekey: aliasto rename. - Default values —
[a = 0]or{ a = 0 }— apply only when the extracted value isundefined. Not fornull,false, or0. - Aliasing with
{ key: newName }lets you rename a property during destructuring without affecting the original object. - Nested destructuring mirrors the shape of the data structure. Keep it to 2 levels max for readability.
- Function parameter destructuring makes function signatures
self-documenting. Always add
= {}as a fallback so the function can be called with no argument. - Destructuring works inside
for...ofloops,Object.entries(),Mapiteration,forEachcallbacks, and ES module imports. - Combine with rest to capture remaining elements:
[head, ...tail]or{ a, ...rest }.
Rate Us on Google
Join Our Learning Community
Connect with thousands of learners, get daily tips, ask questions and stay updated with new tutorials.