Destructuring

📚 Lesson 14 of 22  •  ⏱ 10 min read  •  Intermediate

Array Destructuring

JavaScript
const scores = [95, 82, 78];

// Without destructuring
const first  = scores[0];
const second = scores[1];

// With destructuring
const [first, second, third] = scores;
// first=95, second=82, third=78

// Skip elements with commas
const [top, , third] = scores;  // top=95, third=78

// Default values
const [a = 0, b = 0, c = 0, d = 0] = scores;  // d=0

// Rest
const [best, ...rest] = scores;  // best=95, rest=[82,78]

// Swap variables
let x = 1, y = 2;
[x, y] = [y, x];  // x=2, y=1

Object Destructuring

JavaScript
const user = {
  name: "Priya",
  age: 22,
  city: "Chennai",
  role: "admin"
};

// Basic
const { name, age } = user;  // name="Priya", age=22

// Rename (key: newName)
const { name: userName, city: location } = user;
// userName="Priya", location="Chennai"

// Default values
const { name, active = true } = user;  // active=true (not in user)

// Rest — remaining properties
const { name: n, ...rest } = user;
// n="Priya", rest={age:22, city:"Chennai", role:"admin"}

In Function Parameters

JavaScript
// Without destructuring
function display(user) {
  console.log(user.name, user.age);
}

// With destructuring — cleaner
function display({ name, age, role = "student" }) {
  console.log(name, age, role);
}

display({ name: "Ravi", age: 20 });
// "Ravi" 20 "student"

Nested Destructuring

JavaScript
const response = {
  status: 200,
  data: {
    user: { name: "Kumar", age: 25 },
    posts: ["Post 1", "Post 2"]
  }
};

const { data: { user: { name }, posts: [firstPost] } } = response;
// name="Kumar", firstPost="Post 1"

// Tip: don't over-nest — breaks readability. Do 2 levels max.

Practical: API Response

JavaScript
async function loadUser(id) {
  const res  = await fetch(`/api/users/${id}`);
  const { name, email, avatar, role = "user" } = await res.json();

  return { name, email, avatar, role };
}