Skip to main content
โšก Calmops

Destructuring: Arrays and Objects

Destructuring: Arrays and Objects

Destructuring is a convenient way to extract values from arrays and objects and assign them to variables.

Array Destructuring

Basic Destructuring

const arr = [1, 2, 3];

// Without destructuring
const first = arr[0];
const second = arr[1];

// With destructuring
const [first, second] = arr;
console.log(first); // 1
console.log(second); // 2

Skipping Elements

const arr = [1, 2, 3, 4, 5];

const [first, , third] = arr;
console.log(first); // 1
console.log(third); // 3

Rest Elements

const arr = [1, 2, 3, 4, 5];

const [first, second, ...rest] = arr;
console.log(first); // 1
console.log(second); // 2
console.log(rest); // [3, 4, 5]

Default Values

const arr = [1];

const [first = 10, second = 20] = arr;
console.log(first); // 1
console.log(second); // 20

Swapping Variables

let a = 1;
let b = 2;

[a, b] = [b, a];
console.log(a); // 2
console.log(b); // 1

Object Destructuring

Basic Destructuring

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

// Without destructuring
const name = person.name;
const age = person.age;

// With destructuring
const { name, age } = person;
console.log(name); // "Alice"
console.log(age); // 30

Renaming Variables

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

const { name: personName, age: personAge } = person;
console.log(personName); // "Alice"
console.log(personAge); // 30

Default Values

const person = { name: "Alice" };

const { name, age = 25, city = "Unknown" } = person;
console.log(name); // "Alice"
console.log(age); // 25
console.log(city); // "Unknown"

Rest Properties

const person = { name: "Alice", age: 30, city: "New York", country: "USA" };

const { name, age, ...rest } = person;
console.log(name); // "Alice"
console.log(age); // 30
console.log(rest); // { city: "New York", country: "USA" }

Nested Destructuring

const user = {
    name: "Alice",
    address: {
        street: "123 Main St",
        city: "New York",
        zip: "10001"
    }
};

const { name, address: { city, zip } } = user;
console.log(name); // "Alice"
console.log(city); // "New York"
console.log(zip); // "10001"

Function Parameters

Array Parameters

function sum([a, b]) {
    return a + b;
}

console.log(sum([5, 3])); // 8

Object Parameters

function displayUser({ name, age }) {
    console.log(`${name} is ${age} years old`);
}

displayUser({ name: "Alice", age: 30 }); // "Alice is 30 years old"

Default Values in Parameters

function createUser({ name, role = "user", active = true } = {}) {
    return { name, role, active };
}

console.log(createUser({ name: "Alice" }));
// { name: "Alice", role: "user", active: true }

console.log(createUser());
// { name: undefined, role: "user", active: true }

Practical Examples

Extracting API Response

const response = {
    status: 200,
    data: {
        id: 1,
        name: "Alice",
        email: "[email protected]"
    },
    message: "Success"
};

const { status, data: { name, email } } = response;
console.log(status); // 200
console.log(name); // "Alice"
console.log(email); // "[email protected]"

Function with Multiple Return Values

function getUserInfo(userId) {
    // Simulated API call
    return {
        id: userId,
        name: "Alice",
        email: "[email protected]",
        role: "admin"
    };
}

const { name, email, role } = getUserInfo(1);
console.log(`${name} (${role}): ${email}`);

Array of Objects

const users = [
    { id: 1, name: "Alice" },
    { id: 2, name: "Bob" },
    { id: 3, name: "Charlie" }
];

const [{ name: firstName }, , { name: thirdName }] = users;
console.log(firstName); // "Alice"
console.log(thirdName); // "Charlie"

Combining with Spread Operator

const arr1 = [1, 2];
const arr2 = [3, 4];

const [first, ...middle] = arr1;
const combined = [first, ...middle, ...arr2];
console.log(combined); // [1, 2, 3, 4]

Configuration Objects

function setupServer(config = {}) {
    const {
        host = "localhost",
        port = 3000,
        ssl = false,
        timeout = 5000
    } = config;
    
    return {
        host,
        port,
        ssl,
        timeout
    };
}

console.log(setupServer({ port: 8080, ssl: true }));
// { host: "localhost", port: 8080, ssl: true, timeout: 5000 }

Filtering with Destructuring

const users = [
    { id: 1, name: "Alice", active: true },
    { id: 2, name: "Bob", active: false },
    { id: 3, name: "Charlie", active: true }
];

const activeUsers = users
    .filter(({ active }) => active)
    .map(({ id, name }) => ({ id, name }));

console.log(activeUsers);
// [{ id: 1, name: "Alice" }, { id: 3, name: "Charlie" }]

Advanced Patterns

Computed Property Names

const key = "name";
const obj = { name: "Alice", age: 30 };

const { [key]: value } = obj;
console.log(value); // "Alice"

Destructuring in for…of Loop

const users = [
    { id: 1, name: "Alice" },
    { id: 2, name: "Bob" }
];

for (const { id, name } of users) {
    console.log(`${id}: ${name}`);
}

Destructuring with Aliases

const person = {
    firstName: "Alice",
    lastName: "Smith",
    email: "[email protected]"
};

const {
    firstName: first,
    lastName: last,
    email
} = person;

console.log(first); // "Alice"
console.log(last); // "Smith"

Common Mistakes

Forgetting Parentheses in Object Destructuring

// Error - looks like a code block
// { name, age } = person;

// Correct
const { name, age } = person;

// Or with existing variables
({ name, age } = person);

Destructuring Non-Existent Properties

const obj = { a: 1 };

const { a, b } = obj;
console.log(a); // 1
console.log(b); // undefined (not an error)

Nested Destructuring Errors

const obj = { a: { b: 1 } };

// This will error if obj.a is undefined
const { a: { b } } = obj;

// Better - use default values
const { a: { b } = {} } = obj;

Summary

  • Array destructuring: const [a, b] = arr
  • Object destructuring: const { name, age } = obj
  • Renaming: const { name: personName } = obj
  • Default values: const { name = "Unknown" } = obj
  • Rest elements: const [first, ...rest] = arr
  • Nested: const { a: { b } } = obj
  • Function parameters: destructure in function signature

Official Documentation

Next Steps

  1. Spread Operator and Rest Parameters
  2. Arrow Functions and Function Expressions
  3. Array Methods: map, filter, reduce, forEach

Comments