Skip to content

Destructuring

Destructuring assignment allows unpacking values from arrays or properties from objects into distinct variables. Introduced in ES6 (2015), it provides concise syntax for extracting multiple values.

You had to manually extract each value:

// Arrays
const arr = [1, 2, 3];
const first = arr[0];
const second = arr[1];
const third = arr[2];
// Objects
const user = { name: "Alice", age: 25, city: "NYC" };
const name = user.name;
const age = user.age;
const city = user.city;
// Function parameters
function greet(user) {
return `Hello, ${user.name} from ${user.city}`;
}

Destructuring provides clean one-liner extraction:

// Array destructuring
const [first, second, third] = [1, 2, 3];
const [a, , c] = [1, 2, 3]; // skip middle element
const [x, y, ...rest] = [1, 2, 3, 4, 5]; // rest = [3, 4, 5]
// Object destructuring
const { name, age, city } = { name: "Alice", age: 25, city: "NYC" };
// Renaming
const { name: userName, age: userAge } = user;
// Default values
const { country = "USA" } = user;
// Nested destructuring
const data = {
user: { name: "Bob", address: { city: "LA" } }
};
const { user: { address: { city: userCity } } } = data;
// Function parameters
function greet({ name, city }) {
return `Hello, ${name} from ${city}`;
}
greet({ name: "Alice", city: "NYC" });
// Swapping variables
let a = 1, b = 2;
[a, b] = [b, a]; // swap!
  • Concise: One line instead of multiple assignments
  • Readable: Clear intent of what youโ€™re extracting
  • Flexible: Skip elements, use defaults, rename
  • Function params: Clean extraction of object properties
  • Swapping: Easy variable swapping without temp variable
  • Destructuring undefined or null throws TypeError
  • Can combine with default parameters in functions
  • Rest operator (...) must be last in destructuring
  • Can destructure nested structures (but can get hard to read)
  • Array destructuring uses position; object uses property names
// TypeError if undefined/null
const { x } = null; // TypeError!
// Safe with default
const { x } = obj || {};
// Mixed with defaults in functions
function createUser({
name = "Guest",
age = 0,
premium = false
} = {}) {
return { name, age, premium };
}
createUser(); // { name: "Guest", age: 0, premium: false }
  1. Extract title and author from const book = { title: "1984", author: "Orwell", year: 1949 }

    Answer
    const { title, author } = book;
  2. Get the first and third elements from [10, 20, 30, 40]

    Answer
    const [first, , third] = [10, 20, 30, 40];
  3. Swap x and y in one line using destructuring

    Answer
    [x, y] = [y, x];