← JS Mastery | Module 4: Objects & Arrays Destructuring Assignment
Module 4

Destructuring Assignment

⏱ 18 min read ● Intermediate 🆓 Free

Object Destructuring

Destructuring is a concise syntax to extract values from objects and arrays into variables. It makes code more readable and reduces repetition.

// Old way:
const user = { name: "Alice", age: 30, city: "NYC" };
const name = user.name;
const age = user.age;

// Destructuring:
const { name, age } = user;
console.log(name, age);  // "Alice" 30

// Rename during destructuring:
const { name: userName, age: userAge } = user;
console.log(userName, userAge);  // "Alice" 30

// Default values:
const { name, role = "user" } = user;
console.log(role);  // "user" — default since user.role is undefined

// Nested destructuring:
const profile = {
  user: {
    name: "Bob",
    address: { city: "LA", zip: "90210" }
  }
};
const { user: { name: pName, address: { city } } } = profile;
console.log(pName, city);  // "Bob" "LA"

// In function parameters — very common pattern:
function displayUser({ name, age, city = "Unknown" }) {
  console.log(`${name}, ${age}, from ${city}`);
}
displayUser({ name: "Alice", age: 30 });

Array Destructuring

const rgb = [255, 128, 0];

// Basic array destructuring:
const [r, g, b] = rgb;
console.log(r, g, b);  // 255 128 0

// Skip elements:
const [first, , third] = [1, 2, 3];
console.log(first, third);  // 1 3

// Default values:
const [a = 0, b = 0, c = 0, d = 0] = [1, 2];
console.log(a, b, c, d);  // 1 2 0 0

// Rest in destructuring:
const [head, ...tail] = [1, 2, 3, 4, 5];
console.log(head);  // 1
console.log(tail);  // [2,3,4,5]

// Swap variables:
let x = 1, y = 2;
[x, y] = [y, x];
console.log(x, y);  // 2 1

// Destructure function return:
function getCoordinates() {
  return [40.7128, -74.0060];
}
const [lat, lng] = getCoordinates();

// Destructure from Map.entries():
const map = new Map([["a", 1], ["b", 2]]);
for (const [key, value] of map) {
  console.log(key, value);
}

Real-World Destructuring Patterns

// React hook pattern:
const [count, setCount] = useState(0);

// API response destructuring:
async function loadUser(id) {
  const response = await fetch(`/api/users/${id}`);
  const { data: { user }, status, message } = await response.json();
  return user;
}

// Express route handler:
app.post("/users", ({ body: { name, email, password } }, res) => {
  // Clean, no need for req.body.name everywhere
});

// Destructuring in loops:
const items = [
  { id: 1, name: "Apple", price: 1.5 },
  { id: 2, name: "Banana", price: 0.5 }
];
for (const { id, name, price } of items) {
  console.log(`${id}: ${name} - $${price}`);
}

// Object.entries with destructuring:
const scores = { Alice: 95, Bob: 87, Charlie: 92 };
for (const [name, score] of Object.entries(scores)) {
  console.log(`${name}: ${score}`);
}

⚡ Key Takeaways

🎯 Practice Exercises

EXERCISE 1

Destructure this nested config object to extract: database host, port, and name; and the first API key from an array. { db: { host, port, name }, apiKeys: ["key1","key2"] }

EXERCISE 2

Write a function that accepts a config object and uses destructuring with defaults for all parameters. Test with partial configs.

← Arrays