ES6+ Features
Lesson Progress0%
Destructuring
Topic Overview
Take your time to understand each concept. Practice with the examples below!
Destructuring is like unpacking a suitcase - instead of taking items out one by one, you can grab multiple things at once! It's a shortcut for extracting values from objects and arrays.
Object Destructuring (unpacking objects):
// Old way:const person = { name: "Alice", age: 30, city: "Paris" };const name = person.name;const age = person.age;const city = person.city;// New way with destructuring:const { name, age, city } = person;// Now you have three variables: name, age, and city!
Array Destructuring (unpacking arrays):
// Old way:const colors = ["red", "green", "blue"];const firstColor = colors[0];const secondColor = colors[1];// New way:const [firstColor, secondColor] = colors;
Advanced features:
- •Skip items:const [first, , third] = [1, 2, 3];
- •Rename:const { name: userName } = person;
- •Defaults:const { name = "Guest" } = {};
- •Rest:const [head, ...tail] = [1, 2, 3, 4];
Real-world example:
// Function that returns multiple valuesfunction getCoordinates() { return { x: 10, y: 20 };}const { x, y } = getCoordinates();console.log(`Position: ${x}, ${y}`);Why use destructuring?• Less typing, cleaner code• Extract only what you need• Great for function parameters• Makes code more readable
Ready to practice? Try the exercise below to reinforce your learning!
Try it yourself
Use destructuring to extract values from an object and array.
Loading...