JavaScript Lesson 15: Destructuring

⚡ JavaScript CourseLesson 15 of 20 · 75% complete

Destructuring lets you unpack values from arrays or objects into variables in a clean, readable way. It’s everywhere in modern JavaScript.

Array Destructuring

const colors = ["red", "green", "blue", "yellow"];

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

// Destructuring
const [first, second] = colors;
console.log(first);   // "red"
console.log(second);  // "green"

// Skip elements
const [, , third] = colors;
console.log(third);   // "blue"

// Rest elements
const [head, ...tail] = colors;
console.log(head);  // "red"
console.log(tail);  // ["green", "blue", "yellow"]

// Default values
const [a = 1, b = 2, c = 3] = [10, 20];
console.log(c);  // 3 (default)

Object Destructuring

const person = { name: "Alice", age: 30, city: "London" };

// Old way
const personName = person.name;
const personAge = person.age;

// Destructuring
const { name, age, city } = person;
console.log(name, age, city);  // Alice 30 London

// Rename while destructuring
const { name: userName, age: userAge } = person;
console.log(userName);  // Alice

// Default values
const { name, email = "N/A" } = person;
console.log(email);  // "N/A" (not in object)

Destructuring in Function Parameters

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

// With destructuring — cleaner!
function displayUser({ name, age, city = "Unknown" }) {
  console.log(`${name}, ${age} - ${city}`);
}

displayUser({ name: "Alice", age: 30, city: "London" });
// Alice, 30 - London

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

🏋️ Practice Task

Create an array of 5 user objects with name, email, age. Destructure the first user to get name and email. Write a function printUserCard({name, email, age = “unknown”}) that prints formatted user info. Test with users that have and without age.

💡 Hint: Use const [{name, email}] = users to get first user. Arrow function: const printUserCard = ({name,email,age=”unknown”}) => …

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *