Chapter 20 of 31

JavaScript Destructuring

When working with arrays and objects, we often need to take values out of them and store those values in separate variables.

Without destructuring, we might write:

const person = {
    name: "John",
    age: 25,
    city: "Delhi"
};

const name = person.name;
const age = person.age;
const city = person.city;

This works perfectly fine, but JavaScript provides a cleaner way to do the same thing.

It's called destructuring.

What is Destructuring?

Destructuring is a JavaScript feature that allows us to extract values from arrays or properties from objects and store them in variables in a concise way.

There are two main types:

  • Object destructuring

  • Array destructuring

Let's look at both.


Object Destructuring

Suppose we have an object:

const person = {
    name: "John",
    age: 25,
    city: "Delhi"
};

Instead of:

const name = person.name;
const age = person.age;

we can write:

const { name, age } = person;

console.log(name);
console.log(age);

Output:

John
25

That's much shorter.

The variable names match the object property names:

name → person.name
age  → person.age

Extracting Specific Properties

We don't have to extract every property.

const person = {
    name: "John",
    age: 25,
    city: "Delhi"
};

const { name, city } = person;

console.log(name);
console.log(city);

Output:

John
Delhi

The age property is simply ignored.


Renaming Variables

Sometimes we want to use a different variable name.

For example:

const person = {
    name: "John",
    age: 25
};

const { name: userName, age: userAge } = person;

console.log(userName);
console.log(userAge);

Output:

John
25

Here:

name → userName
age  → userAge

The original object properties don't change. We're simply choosing different variable names.


Default Values

We can provide a default value in case a property doesn't exist.

const person = {
    name: "John"
};

const { name, age = 18 } = person;

console.log(name);
console.log(age);

Output:

John
18

Since age doesn't exist in the object, JavaScript uses the default value 18.

If the property exists, its value is used instead:

const person = {
    name: "John",
    age: 25
};

const { age = 18 } = person;

console.log(age);

Output:

25

Nested Object Destructuring

We can also destructure nested objects.

const user = {
    name: "John",
    address: {
        city: "Delhi",
        country: "India"
    }
};

const {
    address: { city, country }
} = user;

console.log(city);
console.log(country);

Output:

Delhi
India

This is useful when working with deeply structured data, such as API responses.


Array Destructuring

Destructuring also works with arrays.

Suppose we have:

const colors = ["Red", "Green", "Blue"];

We can extract the values like this:

const [first, second, third] = colors;

console.log(first);
console.log(second);
console.log(third);

Output:

Red
Green
Blue

Unlike object destructuring, array destructuring is based on position.

Index 0 → first
Index 1 → second
Index 2 → third

Skipping Array Elements

We can skip values using commas.

const colors = ["Red", "Green", "Blue"];

const [first, , third] = colors;

console.log(first);
console.log(third);

Output:

Red
Blue

Here, the second value "Green" was skipped.


Default Values in Arrays

Just like objects, arrays can have default values.

const numbers = [10];

const [a, b = 20] = numbers;

console.log(a);
console.log(b);

Output:

10
20

Since there is no second value, JavaScript uses the default 20.


Rest Pattern

The rest pattern allows us to collect the remaining values.

const numbers = [10, 20, 30, 40, 50];

const [first, second, ...remaining] = numbers;

console.log(first);
console.log(second);
console.log(remaining);

Output:

10
20
[30, 40, 50]

Here:

first     → 10
second    → 20
remaining → [30, 40, 50]

The ... syntax collects all remaining values.


Rest Pattern with Objects

We can also use the rest pattern with objects.

const person = {
    name: "John",
    age: 25,
    city: "Delhi"
};

const { name, ...details } = person;

console.log(name);
console.log(details);

Output:

John
{ age: 25, city: "Delhi" }

This is useful when we want one or two specific properties and want to collect everything else separately.


Destructuring Function Parameters

Destructuring is especially useful with functions.

Instead of:

function displayUser(user) {
    console.log(user.name);
    console.log(user.age);
}

we can destructure the object directly in the function parameter:

function displayUser({ name, age }) {
    console.log(name);
    console.log(age);
}

const user = {
    name: "John",
    age: 25
};

displayUser(user);

Output:

John
25

This is very common in modern JavaScript, especially when working with functions that receive objects.


Swapping Variables

Destructuring provides a very convenient way to swap two variables.

Normally, you might need a temporary variable:

let a = 10;
let b = 20;

let temp = a;
a = b;
b = temp;

With array destructuring:

let a = 10;
let b = 20;

[a, b] = [b, a];

console.log(a);
console.log(b);

Output:

20
10

Pretty neat!


Destructuring in Loops

Destructuring can also make loops cleaner.

For example:

const users = [
    { name: "John", age: 20 },
    { name: "Alex", age: 22 }
];

for (const { name, age } of users) {
    console.log(name, age);
}

Output:

John 20
Alex 22

Instead of repeatedly writing user.name and user.age, we directly extract the properties we need.


Object vs Array Destructuring

The main difference is simple:

Object Destructuring

Array Destructuring

Uses {}

Uses []

Based on property names

Based on position

const { name } = user

const [first] = colors

Order doesn't matter

Order matters

For example:

const person = {
    name: "John",
    age: 25
};

const { age, name } = person;

This works regardless of order because object destructuring uses property names.

But with arrays:

const colors = ["Red", "Green"];

const [first, second] = colors;

first always gets the first element and second gets the second element.


A Practical Example

Imagine an API gives us user information:

const user = {
    name: "John",
    email: "john@example.com",
    address: {
        city: "Delhi",
        country: "India"
    }
};

Instead of repeatedly accessing properties:

console.log(user.name);
console.log(user.email);
console.log(user.address.city);

we can use destructuring:

const {
    name,
    email,
    address: { city }
} = user;

console.log(name);
console.log(email);
console.log(city);

Output:

John
john@example.com
Delhi

This makes code much cleaner, especially when working with large objects.

Conclusion

Destructuring allows us to extract values from arrays and objects and store them in variables using a clean and concise syntax.

The two main forms are:

// Object destructuring
const { name, age } = person;

// Array destructuring
const [first, second] = colors;

The most important things to remember are:

  • {} is used for object destructuring.

  • [] is used for array destructuring.

  • Object destructuring works using property names.

  • Array destructuring works using positions.

  • Default values can be provided.

  • ... can collect remaining values.

  • Destructuring is commonly used with function parameters and loops.

Once you get comfortable with destructuring, modern JavaScript code becomes much easier to read and write, especially when working with objects, arrays, APIs, and functions.