Curriculum / Intermediate / Lesson 12

Destructuring

Unpacking arrays and objects cleanly with modern syntax.

12 of 30
intermediate 📖 5 min read 🎯 3 questions

What is Destructuring?

Destructuring is a way to extract values from arrays or objects and assign them to variables in a clean, readable way.

💡 Key insight Destructuring makes it easy to extract multiple values from complex data structures with less code.

Array Destructuring

let colors = ["red", "green", "blue"];

// Old way
let first = colors[0];
let second = colors[1];

// Destructuring
let [firstColor, secondColor] = colors;
console.log(firstColor); // "red"

// Skipping elements
let [first, , third] = colors;
console.log(third); // "blue"

Object Destructuring

let person = { name: "Alice", age: 25, city: "New York" };

// Old way
let name = person.name;
let age = person.age;

// Destructuring
let { name, age } = person;
console.log(name); // "Alice"

// Renaming variables
let { name: personName, age: personAge } = person;

Default Values

let person = { name: "Alice" };

let { name, age = 30 } = person;
console.log(age); // 30 (default value)

Nested Destructuring

let user = {
  id: 1,
  profile: {
    name: "Alice",
    email: "alice@example.com"
  }
};

let { profile: { name, email } } = user;
console.log(name); // "Alice"

Common Mistakes

Quick Quiz

1. What does let [a, b] = [1, 2, 3]; do?

2. What does let { name } = { name: "Alice", age: 25 }; do?

3. How do you rename a variable in object destructuring?

Summary

Back to curriculum