DEV Community

Cover image for Destructuring of Arrays and Objects in Javascript
Benjamin Busari
Benjamin Busari

Posted on • Edited on

Destructuring of Arrays and Objects in Javascript

# Destructuring of Arrays and Objects in Javascript
Enter fullscreen mode Exit fullscreen mode

This piece aims to simplify destructuring of arrays and objects while also explaining the use of the SPREAD operator. This should be quite useful for javascript beginners new to this concept also you can look up my other piece on Destructuring Props and States.

Excited to learn something new😀? Then let’s dive in!.

What is Destructuring?

In layman’s terms, Destructuring is the process of breaking a structure. In the context of programming, the structures are the data structures, and destructuring these data structures means unpacking individual values from the data structure.

Destructuring in JavaScript is a convenient way of extracting data from arrays or objects, mapping and setting them into new, distinct variables. It efficiently allows the extraction of multiple properties or items from an array or an object.

With the syntax of destructuring, you can extract smaller fragments from objects and
arrays. It can be used for assignments and declaration of a variable.

Destructuring an Array

When destructuring in javascript, a syntax you would want to keep in mind would be placing the element you want to destructure on the right side of the assignment operator and placing the variable you want to access on the left side of the assignment operator. The variables should be in { } when destructuring objects and [ ] when destructuring arrays.

Lets look at the code below:

const alphabets = ['A', 'B', 'C', 'D', 'E', 'F']

const a = alphabets[0]

console.log(a)

//The code will display **A** in the console
Enter fullscreen mode Exit fullscreen mode

The above code contains an array of alphabets. Now a way to access an element in the array alphabet would be to target the index of the element in that array and assign it to a variable, then you display the result of that variable in the console as seen above or you can try this:

**console.log(alphabets[index]).**
Enter fullscreen mode Exit fullscreen mode

But with destructuring in an array you can access multiple data in that array without having to target their index. Let’s try this below:

const alphabets = ['A', 'B', 'C', 'D', 'E', 'F']

const [firstAlphabet, secondAlphabet] = alphabets;

console.log(firstAlphabet);
console.log(secondAlphabet);

// Try the code in your Editor and see the result 🙂. 
// The first element in the array will be assigned to firstAlphabet variable
// Also the second element in the array will be assigned to secondAlphabet variable

//Hence the console will display A and then B
Enter fullscreen mode Exit fullscreen mode

Just like I had earlier explained, the element we want to destructure is placed on the right side of the assignment operator and the data you want to access is placed on the left side of the assignment operator, both items are in [ ] because we are destructuring an array.

JavaScript will parse the alphabets array and copy its first value ('A') into the destructuring array’s first variable (firstAlphabet).

Likewise, the computer will extract the alphabets array’s second value ('B') into the destructuring array’s second variable (secondAlphabet).

This way, we can extract not just one but multiple data from the array without having to use an index.

Destructuring an Object

Now the same syntax applies to destructuring of objects { }, let’s assume you have an object and you would like to access a property, value, etc in the object. Destructuring the object comes in handy, making life easier for you and me.

Let’s look at the code below:

const user = {
    name: "John",
    email: "JohnDoe@gmail.com",
    password: "JohnXX3346",
    address : {
        city: "ikeja",
        state: "Lagos",
        country: "Nigeria",
    }
}
console.log(user.address.city);
Enter fullscreen mode Exit fullscreen mode

The above is an object User with data stored in it, now the conventional way to access information about the city of the User would be to console.log(user.address.city) as shown above. But with Object Destructuring you can access city and any other value easily.

Let’s look at the code below:

const user = {
    name: "John",
    email: "JohnDoe@gmail.com",
    password: "JohnXX3346",
    address : {
        city: "ikeja",
        state: "Lagos",
        country: "Nigeria",
    }
}
const {city} = user.address;

console.log(city);
Enter fullscreen mode Exit fullscreen mode

Tried it? 🙂. What happened? The console outputs Ikeja , another way to go about this would be like this:

const user = {
    name: "John",
    email: "JohnDoe@gmail.com",
    password: "JohnXX3346",
    address : {
        city: "ikeja",
        state: "Lagos",
        country: "Nigeria",
    }
}
const {address: {city} } = user;
Enter fullscreen mode Exit fullscreen mode

What do you think? 🤔

Destructuring in Function

We have clearly seen how to destructure arrays and objects. Are you finding it interesting?

We can destructure in functions too. Lets take a look at the code below:

const user = {
    name: "John",
    email: "JohnDoe@gmail.com",
    password: "JohnXX3346",
    address : {
        city: "ikeja",
        state: "Lagos",
        country: "Nigeria",
    }
}
function displayUser(info){
    console.log(info);
}
displayUser(user);

//you can also try display(user.name) to get name value, 
(user.address.city) to display city value 🙂 KEEP GOING!
Enter fullscreen mode Exit fullscreen mode

The above code would display info that contains all data in the user object. Now with destructuring, we can rewrite this code to make access to values and properties easier.
How do we go about this? Let’s look at the code below:

const user = {
    name: "John",
    email: "JohnDoe@gmail.com",
    password: "JohnXX3346",
    address : {
        city: "ikeja",
        state: "Lagos",
        country: "Nigeria",
    }
}
function displayUser({name, email}){
    console.log(`My name is ${name} and here is my email: ${email}`);
}
displayUser(user);

//What was your result? Cool right 😉.
//You should see **My name is John and here is my email: JohnDoe@gmail.com** displayed in the console
Enter fullscreen mode Exit fullscreen mode

Unlike the previous code, all we had to do here was to insert the properties we want to get their values in as arguments, not forgetting to put them in curly braces { }, then we console.log the result, and as you can see we made use of template strings. For more understanding of template strings, you can look up this amazing piece on Template Strings by Digital Ocean.

Conclusion

Destructuring in Javascript is a powerful feature that lets you extract properties from an object and bind these values to variables.
What I find interesting about destructuring is the concise syntax and ability to extract multiple variables in one statement also as you would see, it allows cleaner code which is one of the best practices for coding in Javascript.

I hope you enjoyed this tutorial, be sure to like, comment and give your feedback on this and also indicate what topic you would also like me to write on. Cheers! 😉

Top comments (0)