All you need to know about Destructuring in javascript

Table of contents

No heading

No headings in the article.

Destructuring is a way you can extract data from arrays or objects and give them a name.

let's imagine I have an array like this:

const names = ["Emeka", "Felicia", "Kayla", "Nancy"];

I may want to put the first value in a variable. We can say:

const emeka = names[0];
console.log(Emeka); //Emeka

But with destructuring it will look like this instead:

const [Emeka] = names;
console.log(Emeka); // Emeka

If I want to put all four items in a variable, it will look like this with destructuring below:

 const [Emeka, Felicia, Kayla, Nancy] = names;

And without destructuring it will look like this:

const Emeka = names[0];
const Felicia = names[1];
const Kayla = names[2];
const Nancy = names[3];

USING DESTRUCTURING FOR OBJECTS

This is what it looks like destructuring using an object

const person = {
firstName: "Ronaldo",
age: 37,
address: {
        street: "3, Al Nassr",
        city: 'Riyadh",
        }
}
const {firstName, age, address} = person;
console.log(firstName); //Ronaldo
console.log(age);   // 37
console.log(address);   // {street: "3, Al Nassr", city: 'Riyadh"}

YOU CAN COMBINE DESTRUCTURING WITH THE SPREAD OPERATOR

You can even combine destructuring with the spread operator to get the rest of the values.

const person = {
firstName: "Ronaldo",
age: 37,
address: {
        street: "3, Al Nassr",
        city: 'Riyadh",
        }
}

const { name, ...otherValues } = person;
console.log(otherValues);   // { age: 37, address: { street: "3, Al Nassr", city: 'Riyadh" } }

DESTRUCTURING CAN ALSO BE USED IN FUNCTION ARGUMENTS

const person = {
firstName: "Emeka"
}

const sayHi({name}){ //here destructuring the person object
    console.log(`Hi, my name is ${name}`); // here extracting the name key
}
sayHi(person); //passing the person object as an argument

What's happening here? you may wonder....

Firstly, we are destructuring the person object that has been passed in and we are extracting the name key into the name variable. Then we pass the person object as an argument.