Destructuring
Destructuring
Section titled “Destructuring”What it is
Section titled “What it is”Destructuring assignment allows unpacking values from arrays or properties from objects into distinct variables. Introduced in ES6 (2015), it provides concise syntax for extracting multiple values.
Before this feature
Section titled “Before this feature”You had to manually extract each value:
// Arraysconst arr = [1, 2, 3];const first = arr[0];const second = arr[1];const third = arr[2];
// Objectsconst user = { name: "Alice", age: 25, city: "NYC" };const name = user.name;const age = user.age;const city = user.city;
// Function parametersfunction greet(user) { return `Hello, ${user.name} from ${user.city}`;}After this feature
Section titled “After this feature”Destructuring provides clean one-liner extraction:
// Array destructuringconst [first, second, third] = [1, 2, 3];const [a, , c] = [1, 2, 3]; // skip middle elementconst [x, y, ...rest] = [1, 2, 3, 4, 5]; // rest = [3, 4, 5]
// Object destructuringconst { name, age, city } = { name: "Alice", age: 25, city: "NYC" };
// Renamingconst { name: userName, age: userAge } = user;
// Default valuesconst { country = "USA" } = user;
// Nested destructuringconst data = { user: { name: "Bob", address: { city: "LA" } }};const { user: { address: { city: userCity } } } = data;
// Function parametersfunction greet({ name, city }) { return `Hello, ${name} from ${city}`;}greet({ name: "Alice", city: "NYC" });
// Swapping variableslet a = 1, b = 2;[a, b] = [b, a]; // swap!Why this is better
Section titled “Why this is better”- Concise: One line instead of multiple assignments
- Readable: Clear intent of what you’re extracting
- Flexible: Skip elements, use defaults, rename
- Function params: Clean extraction of object properties
- Swapping: Easy variable swapping without temp variable
Key notes / edge cases
Section titled “Key notes / edge cases”- Destructuring
undefinedornullthrows TypeError - Can combine with default parameters in functions
- Rest operator (
...) must be last in destructuring - Can destructure nested structures (but can get hard to read)
- Array destructuring uses position; object uses property names
// TypeError if undefined/nullconst { x } = null; // TypeError!
// Safe with defaultconst { x } = obj || {};
// Mixed with defaults in functionsfunction createUser({ name = "Guest", age = 0, premium = false} = {}) { return { name, age, premium };}
createUser(); // { name: "Guest", age: 0, premium: false }Quick practice
Section titled “Quick practice”-
Extract
titleandauthorfromconst book = { title: "1984", author: "Orwell", year: 1949 }Answer
const { title, author } = book; -
Get the first and third elements from
[10, 20, 30, 40]Answer
const [first, , third] = [10, 20, 30, 40]; -
Swap
xandyin one line using destructuringAnswer
[x, y] = [y, x];