Tutorials JavaScript Destructuring
Ch 34 / 78
Chapter 34 Intermediate 9 min read JavaScript

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.

What you'll learn
Array destructuring — extract values by position
Object destructuring — extract values by property name
Default values — fallback when the value is undefined
Renaming / aliasing variables during destructuring
Nested destructuring — unpack deeply nested structures
Function parameter destructuring — real-world React & API patterns

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:

Array Destructuring
Uses square brackets on the left side. Values are extracted by their index position — order matters. You can skip elements with empty commas.
const [a, b, c] = [1, 2, 3];
// a=1 b=2 c=3
Object Destructuring
Uses curly braces on the left side. Values are extracted by their property name — order doesn't matter. Variables must match property keys (or use aliasing).
const { name, age } = user;
// name=user.name age=user.age
// OLD WAY — manual assignment
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 — square brackets, position-based Object — curly braces, name-based Alias — rename with colon : newName Default — fallback with = 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:

Position-based rules
1 Variables on the left map to indices 0, 1, 2… of the array
2 Skip elements with a blank comma , ,
3 Extra variables get undefined if the array is shorter
4 Combine with rest ...tail to capture the remainder
Handy tricks
✓ Swap variables in one line — [a, b] = [b, a]
✓ Return multiple values from a function cleanly
✓ Default values guard against undefined
✓ Works with any iterable — strings, Sets, Maps
JavaScript — Array Destructuring
// ── 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 20

Object 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:

const { key1, key2: alias, key3 = defaultVal } = sourceObject;
key1 — extract as variable named key1 key2: alias — extract key2 but store in variable named alias key3 = defaultVal — use defaultVal if key3 is undefined sourceObject — the object being unpacked (on the right)
JavaScript — Object Destructuring
// ── 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
}
Tip — Default vs Falsy
Default values only apply when the property is 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:

Nested Object Rules
1 Mirror the shape of the source object
2 Use { outer: { inner } } to reach inside
3 Alias still works at any level
Watch Out For
! Deep nesting makes code hard to read — limit to 2 levels
! If an intermediate key is undefined, JavaScript throws TypeError
! Use optional chaining or defaults to guard against missing keys
JavaScript — Nested Destructuring
// ── 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); // undefined

Function 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:

JavaScript — Parameter Destructuring
// ── 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
Always add = {} default
When destructuring an object parameter, always add = {} 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:

JavaScript — Loops, Entries & Imports
// ── 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 = three

Array 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:

React useState
Returns [value, setter] — array destructuring names them on one line: const [count, setCount] = useState(0)
array
API Response Unpacking
Extract only the fields you need from a large API response object — ignore the rest without extra variables.
object
Variable Swap
Swap two variables without a temporary: [a, b] = [b, a] — clean, no extra allocation needed.
array
ES Module Imports
Import named exports: import { useState, useEffect } from "react" — named imports use object destructuring semantics.
object
Multiple Return Values
Functions can "return" multiple values by returning an array, which callers destructure into named variables.
array
Component Props (React)
Destructure props in the parameter — function Card({ title, img, onClick }) — for clean, self-documenting components.
object
Object.entries Loop
Iterate key-value pairs of an object cleanly: for (const [key, val] of Object.entries(obj))
both
Strip Sensitive Fields
Use object rest destructuring to omit properties: const { password, ...safeUser } = user before sending to client.
object
⚡
Free Resource
Download our JavaScript Cheat Sheet
Destructuring, spread, rest & modern JS patterns — all on one page.
Get Sheet

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.

Live Editor
✎ Editor
👁 Preview

Common Patterns & Recipes

Here are the most useful destructuring patterns you'll reach for every day in real JavaScript and modern frameworks:

JavaScript — Destructuring Recipes
// ── 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 8
Quick Check
What is the value of c after const [a, b, c = 99] = [1, 2]?
Quick Check
Given const { name: n } = { name: "Alice" }, which variable holds "Alice"?
Quick Check
When does a destructuring default value kick in?
Chapter Summary
  • 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 use key: alias to rename.
  • Default values — [a = 0] or { a = 0 } — apply only when the extracted value is undefined. Not for null, false, or 0.
  • 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...of loops, Object.entries(), Map iteration, forEach callbacks, and ES module imports.
  • Combine with rest to capture remaining elements: [head, ...tail] or { a, ...rest }.

Rate Us on Google

4.8 / 5
Enjoying this tutorial?
Your 5-star review helps other learners discover our free tutorials and encourages us to keep creating quality content.
80+ reviews
Write a Google Review
Join WhatsApp Channel