18 minLesson 9 of 35
Modern ES6+ JavaScript
Destructuring: Arrays & Objects
Destructuring: Arrays & Objects
Destructuring lets you unpack values from arrays and objects into individual variables with a single, clean syntax. It's used constantly in modern JavaScript — in function parameters, API response handling, React props, and more.
Array Destructuring
// Without destructuring
const rgb = [255, 128, 0];
const red = rgb[0];
const green = rgb[1];
const blue = rgb[2];
// With destructuring — position matters
const [red, green, blue] = [255, 128, 0];
console.log(red); // 255
console.log(green); // 128
console.log(blue); // 0
// Skip elements with commas
const [first, , third] = [1, 2, 3];
console.log(first, third); // 1, 3
// Default values
const [x = 0, y = 0, z = 0] = [10, 20];
console.log(x, y, z); // 10, 20, 0
// Swap variables — elegant and clean
let a = 1, b = 2;
[a, b] = [b, a];
console.log(a, b); // 2, 1
// Rest element
const [head, ...tail] = [1, 2, 3, 4, 5];
console.log(head); // 1
console.log(tail); // [2, 3, 4, 5]
Object Destructuring
const user = { name: "Alice", age: 30, city: "New York", role: "admin" };
// Without destructuring
const name = user.name;
const age = user.age;
// With destructuring — property names must match
const { name, age } = user;
console.log(name, age); // "Alice", 30
// Rename while destructuring
const { name: username, city: location } = user;
console.log(username, location); // "Alice", "New York"
// Default values
const { role = "user", theme = "light" } = user;
console.log(role); // "admin" (from object)
console.log(theme); // "light" (default, not in object)
// Rest properties
const { name: n, ...rest } = user;
console.log(n); // "Alice"
console.log(rest); // { age: 30, city: "New York", role: "admin" }
Nested Destructuring
const response = {
status: 200,
data: {
user: {
id: 42,
name: "Alice",
address: {
city: "NYC",
zip: "10001"
}
}
}
};
// Extract deeply nested values
const { data: { user: { name, address: { city } } } } = response;
console.log(name, city); // "Alice", "NYC"
// Mixed array and object destructuring
const users = [
{ id: 1, name: "Alice" },
{ id: 2, name: "Bob" }
];
const [{ name: first }, { name: second }] = users;
console.log(first, second); // "Alice", "Bob"
Destructuring in Function Parameters
This is where destructuring really shines — cleaner function signatures:
// Old way — accessing properties inside the function
function createUser(options) {
const name = options.name;
const age = options.age || 0;
const role = options.role || "user";
}
// With destructuring in parameters
function createUser({ name, age = 0, role = "user" }) {
return { name, age, role };
}
createUser({ name: "Alice", age: 30 });
// { name: "Alice", age: 30, role: "user" }
// React component props
function Button({ label, onClick, disabled = false, variant = "primary" }) {
return `<button class="btn-${variant}" ${disabled ? "disabled" : ""}>${label}</button>`;
}
// Array destructuring in parameters
function swap([a, b]) {
return [b, a];
}
swap([1, 2]); // [2, 1]
Destructuring with the fetch API
async function loadUser(id) {
const response = await fetch(`/api/users/${id}`);
const { name, email, role, createdAt } = await response.json();
return { name, email, role, createdAt };
}
// Destructuring in loops
const users = await fetchUsers();
for (const { id, name, email } of users) {
console.log(`${id}: ${name} <${email}>`);
}
Destructuring React useState
// useState returns [value, setter] — array destructuring
const [count, setCount] = useState(0);
const [user, setUser] = useState(null);
const [isLoading, setIsLoading] = useState(true);
// Without destructuring it would be:
const countState = useState(0);
const count = countState[0];
const setCount = countState[1];
Destructuring with Import
// Destructuring in ES module imports
import { useState, useEffect, useRef } from "react";
import { createStore, combineReducers } from "redux";
import { BrowserRouter, Route, Link } from "react-router-dom";
// Named exports are destructured just like object properties
Common Patterns
// Safe destructuring with || fallback
const { name = "Unknown", settings: { theme = "light" } = {} } = userPreferences;
// ↑ default for settings if undefined
// Destructure and immediately use
function processApiResponse({ data: { users }, meta: { total, page } }) {
return { users, total, page };
}
// Computed property names in destructuring
const key = "name";
const { [key]: value } = { name: "Alice" };
console.log(value); // "Alice"
Next lesson: Spread & Rest Operators — spreading iterables and collecting the rest.
📱
Get Notes Free →Get this course's notes on Telegram!
Free cheat sheets, summaries & practice exercises