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];