JavaScript Destructuring [In-Depth Tutorial]


JavaScript

Getting started with JavaScript Destructuring

JavaScript destructuring is a powerful feature that allows developers to extract values from objects and arrays and assign them to variables. It can greatly simplify and improve the readability of your code, particularly when working with complex data structures.

There are several approaches to destructuring in JavaScript, each with its own strengths and use cases. These approaches include destructuring arrays, destructuring objects, and destructuring function arguments.

Consider this syntax:

var first = obj.first; // Manual destructuring

That code destructures first by copying it from obj (extracting it from the object structure).

In this article, we will explore each of these approaches in detail and discuss when and how to use them effectively in your code.

 

Simple Examples to understand the concept

As stated earlier, JavaScript destructuring is a way to extract values from arrays, or properties from objects, and assign them to variables. It is a concise way to create variables from data stored in objects and arrays.

For example, consider the following array:

const colors = ['red', 'green', 'blue'];

To extract the values from this array and assign them to separate variables, you could do something like this:

const color1 = colors[0];
const color2 = colors[1];
const color3 = colors[2];

console.log(color1, color2, color3);

Output

red green blue

This works, but it can get cumbersome when you have large arrays or when you need to extract values from nested arrays or objects.

Here's where destructuring comes in handy. You can extract values from arrays or properties from objects and assign them to variables using a syntax that looks like this:

const [color1, color2, color3] = colors;

console.log(color1, color2, color3);

Output

red green blue

This creates three variables, color1, color2, and color3, and assigns them the values of the corresponding elements in the colors array.

You can also use destructuring to extract values from nested arrays or objects.

const data = [
    { id: 1, name: "John" },
    { id: 2, name: "Jane" },
];
const [{ name: user1 }, { name: user2 }] = data;

console.log(user1, user2);

Output

John Jane

This creates two variables, user1 and user2, and assigns them the values of the name property of the objects in the data array.

Let’s show more destructuring examples

 

Destructuring objects

The new syntax gives you a new way to destructure things, usually with less repetition and fewer unnecessary variables. So. instead of writing:

let obj = {first: 1, second: 2};
let a = obj.first;          // Old, manual destructuring
console.log(a);             // 1

you can write:

let obj = {first: 1, second: 2};
let {first: a} = obj;       // New destructuring syntax
console.log(a);             // 1

 

Example-1: You can use destructuring to extract values from objects and assign them to variables. Let’s illustrate this by destructing a person object.

const person = {
    firstName: "John",
    lastName: "Doe",
    age: 30,
};

const { firstName, lastName, age } = person;

console.log(firstName);
console.log(lastName);
console.log(age);

Output

John
Doe
30

 

Example-2: You can also use destructuring to extract values from nested objects. As long as you know the structure of the nested objects, you can easily define them within the destructuring assignment. Here is an example of how to work with destructing in nested objects.

const person = {
    name: {
        first: "John",
        last: "Doe",
    },
    age: 30,
};

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

console.log(firstName);
console.log(lastName);
console.log(age);

Output

John
Doe
30

 

Example-3: Take a look at the following object:

let chair = {
  brand: "Le Chair",
  legs: "4",
  material: "Wood",
  inventory: "42",
  price: "$29.99",
  color: "Blue"
};

We have an object called chair, and it contains a bunch of properties. If we want to extract and store the values of just the brand and price properties, we can do so via destructuring:

let {brand, price} = chair;
 
console.log(brand); // "Le Chair"
console.log(price); // "$29.99"

In our variable declaration and assignment, we are declaring two variables called brand and price whose names match the property names inside the object we are unpacking. The end result is that we are able to work with the values stored by brand and price properties as their own individual variables.

If we wanted to access the remaining properties without any manual bookkeeping, the spread operator exists in this context as well:

let {brand, price, ...rest} = chair;
 
console.log(brand); // "Le Chair"
console.log(price); // "$29.99"
console.log(rest); /* {
                      legs: '4',
                      material: 'Wood',
                      inventory: '42',
                      color: 'Blue'
                     } */

The rest variable stores the results of destructuring our object using the spread operator. What gets returned is a new object whose properties are the ones we haven’t unpacked. In other words, this new object contains everything except the brand and price properties.

 

Destructuring Arrays

You can destructure arrays and other iterables, too. Unsurprisingly, the syntax uses square brackets ([]) instead of the curly braces ({}) used by object destructuring:

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

The value each target receives depends on where it is in the pattern. So with [first, second], first gets the value from arr[0] because it's in the 0th position, and second gets the value from arr[1] because it's in the 1st position. It's just like you'd written:

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

It's valid to leave out elements you don't want. Notice that the following code has no variable in the 0th position:

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

You can leave gaps in the middle, too:

const arr = [1, 2, 3, 4, 5];
const [, b, , , e] = arr;
console.log(b, e); // 2 5

Consider this array:

let winners = ["bear", "cat", "dog", "giraffe", "unicorn"];

If we want to store the first three items from the array in their own variables, here is how we can do that by using destructuring:

let winners = ["bear", "cat", "dog", "giraffe", "unicorn"];
 
let [firstPlace, secondPlace, thirdPlace] = winners;
 
console.log(firstPlace); // bear
console.log(secondPlace); // cat
console.log(thirdPlace); // dog

To print out the remaining items we can use spread operator (...):

let winners = ["bear", "cat", "dog", "giraffe", "unicorn"];
 
let [firstPlace, secondPlace, thirdPlace, ...others] = winners;
 

console.log(firstPlace); // bear
console.log(secondPlace); // cat
console.log(thirdPlace); // dog
console.log(others); // [giraffe, unicorn, dinosaur]

 

How to skip items with comma?

We can see in our examples for array that each variable is comma-separated, and the comma helps indicate when we jump from one item in our array to the next in sequential order.

So what if we want to skip an item from being assigned to a variable. To skip an item (or many items), we need to specify a comma but no variable to pair with the comma.

Take a look at the following example:

let [a, , b] = [1, 2, 3, 4, 5, 6, 7];
 
console.log(a); // 1
console.log(b); // 3

Notice that we specify an empty comma after the a variable. This ends up appearing as two commas, and the result is one where we map only the first item and the third item. The second item is skipped since there is no variable to store that item.

 

How to handle more variables then actual data?

Sometimes we may be trying to map more variables than there is data to map to them. Take a look at the following example:

let [first, second, third] = ["Homer", "Marge"];
 
console.log(first); // "Homer"
console.log(second); // "Marge"
console.log(third); // undefined

The array we are trying to unpack into variables only has two items, but we have three variables. When we have a variable that doesn’t have any data associated with it, that variable is given a value of undefined.

If the undefined value is undesirable, we can specify a default value to override that behavior:

let [first, second, third = "Person"] = ["Homer", "Marge"];
 
console.log(first); // Homer
console.log(second); // Marge
console.log(third); // Person

In this variation, notice that the value for third is set to the default value of Person because it doesn’t have a defined value in the array.

 

Difference between destructuring Arrays and Objects

The destructuring assignment for arrays involves brackets:

let [a, b] = [1, 2]

The destructuring assignment for objects involves curly braces:

let {a, b} = { a: 1, b: 2 }
  • With arrays, the order of our variable names during assignment mapped to the order of our items in the array. With objects, order doesn’t matter. The variable names determine which of our object property values get mapped.
  • With arrays, the spread operator returns a new array whose contents are a consecutive list of array values starting right after the ones we had already mapped. With objects, the spread operator returns a new object made up of the properties we haven’t already mapped. The order of how the properties are defined inside the object doesn’t matter. The only thing that matters is which properties have already been mapped and which ones haven’t.

 

Destructuring function arguments

You can use destructuring to extract values from function arguments. Let’s illustrate this scenario by creating a simple hello function that takes an object.

function hello({ firstName, lastName }) {
    console.log(`Hello, ${firstName} ${lastName}!`);
}

hello({ firstName: "Michael", lastName: "Dell" });

Output

Hello, Michael Dell!

 

Destructuring in for-of loops

You can use destructuring in for-of loops to extract values from arrays or objects. If we want to loop through an object values, we can easily use the destructing to loop through it concisely. Let’s look through the example below.

const data = [
    { id: 1, name: "John" },
    { id: 2, name: "Jane" },
];

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

Output

John has id 1
Jane has id 2

In the code, the for-of loop iterates over the elements of the data array and uses destructuring to extract the id and name properties from each object. The destructured variables id and name are then used in the loop body to log a message to the console that includes the name and id of each object.

 

Summary

Destructuring is a powerful tool that can greatly simplify your code and make it more readable. It is widely used in modern JavaScript development and is a good tool to have in your toolbox. We can use it with arrays, objects, functions and loops to make concise code. Even if you and I have no plans of ever using it in our code, destructuring has gotten so common (especially in frameworks like React and Vue) that we’ll find ourselves forced to use it or needing to review/read code written by someone else that heavily relies on it.

 

References

Destructuring assignment - JavaScript | MDN (mozilla.org)

 

Olorunfemi Akinlua

Olorunfemi Akinlua

He is boasting over five years of experience in JavaScript, specializing in technical content writing and UX design. With a keen focus on programming languages, he crafts compelling content and designs user-friendly interfaces to enhance digital experiences across various domains. You can connect with him on his LinkedIn profile.

Can't find what you're searching for? Let us assist you.

Enter your query below, and we'll provide instant results tailored to your needs.

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

Buy GoLinuxCloud a Coffee

For any other feedbacks or questions you can send mail to admin@golinuxcloud.com

Thank You for your support!!

Leave a Comment