How to use De-structuring in JavaScript ? [Part-1]

How to use De-structuring in JavaScript ? [Part-1]

Destructuring is a feature used to extract values from an Array or Object in separate variables. Destructuring helps us to break down an Array or Object into variables.
The destructuring assignment was introduced in ECMAScript 2015 or ES6 and is been used by developers for various purposes.

In this article, you will learn what is destructuring and how to use destructuring for an Array.

Table Contents


Why use Destructuring?

Before answering the How we will discuss Why we need Destructuring in the first place.

  • Let us consider a scenario where you are making a meal-making 🍛application and while coding you have an array having a list of items in a specific order [a fruit, a vegetable, a sauce, a cheese]. Now you want to segregate these array elements into their specific variables.

So what will a person do who doesn't know destructuring. They will try to extract values by using their indexes as shown.

const items=["Mango","Onion","Soy","Cheddar"];
const fruit=items[0];
const vegetable=items[1];
const sauce=items[2];
const cheese=items[3];
console.log(fruit,vegetable,sauce,cheese);// we get Mango Onion Soy Cheddar as output

Now the elements of array got extracted into their specific variables. Great Job ! Now lets improve this solution using Destructuring.

const items=["Mango","Onion","Soy","Cheddar"];
const [fruit,vegetable,sauce,cheese]=items;
console.log(fruit,vegetable,sauce,cheese);// we get Mango Onion Soy Cheddar as output

That is it , we have successfully destructured items array into fruit,vegetable,sauce and cheese variable. Hope so you understood by looking at the above code examples how destructuring helps to make code more efficient by unpacking the values of an array into variables.

NOTE: While destructuring the original array do not get affected it remains as it is. The items array remain as it is.


Basic Syntax and how to skip a variable

The basic syntax for destructuring an Array is as follow :

const [variable1,variable2,variable3]= Array;

Don't get confused by the " [ ] " on the left-hand side to be an array. When " [ ] " is on the LHS of the assignment operator(=) then JavaScript interprets it as Destructuring Assignment.

How to skip a variable while destructuring?

Let us consider the example that we used in Why use Destructuring ?.

  • Here a person doesn't want vegetables in his meal🍛[He/she don't take their veggies 😬] and wants to skip that by not assigning it to any variable.

So in while destructuring we have to just leave a blank space in the position of the variable which we have to skip.

const items=["Mango","Onion","Soy","Cheddar"];
const [fruit, ,sauce,cheese]=items;
console.log(fruit,sauce,cheese)// Mango Soy Cheddar ( This man is a dummy. How can one not like vegetables? Everyone likes vegetables, don't you😬?)

Switching Variables

If you are enrolled in any CS course/degree then you may have definitely in your initial days have gone through this problem in which we have to interchange values of two variables.

Destructuring will make it too easy for you. Lets go through the normal way which I guess all CS undergrads have gone through

let a=2;
let b=3;
const temp = a;
a=b;
b=temp;
console.log(a,b) // 3 2

Now let us do this the more efficient way by using destructuring.

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

So what happened here. First, as you can see we assigned "a" to 2 and "b" to 3. After that we used destructuring for an array at the right-hand side of the " = " which contains variables [b, a] whose values are [3,2] which now gets assigned to the variables inside the destructuring assignment on the left-hand side. Those are "a" and "b". Therefore, "a" becomes 3 and "b" becomes 2.


Nested Destructuring

Now we will learn to extract all the values from a Nested array. For this, we will use nested destructuring which is easy to use and if you saw the below example you will understand it.

const items=["Mango","Onion","Soy",["Cheddar","Mozzarella"]];
// Here we have an Nested array
const [fruit,vegetable,sauce,[cheese1,cheese2]]=items;
// Here is how we use nested destructuring
console.log(cheese1,cheese2);
//Cheddar Mozzarella

Here as we can see the two types of cheese are nested inside the items array. So to unpack them we used nested destructuring.


Setting default values for the variables

Now there may be a situation where you will be fetching an array from an API and you might not know how many elements are there inside that array but you know that you want the first 5 elements from the array in 5 variables.

But what to do if there are less than 5 elements in the fetched array?
What valued will we assign to the remaining variables?
Here is where default values for the variables come into play.

  • Okay let's assume you are giving your online exam🖥️ and you are stuck while solving true ✔️or false❌ problems. Your friend was only able to cheat you first 3 answers(even though he promised he will answer all 5 😑) but you are accepting for 5 answers and if nothing get assigned to the last two variables your teacher may get a doubt on you and check if you have done any malpractices😨. Who will save you 🤔 ?

Default values

const friendsAns=[true,false,false];
const [myans1,myans2,myans3,myans4=true,myans5=true]=friendsAns;
console.log(myans4,myans5); // true true (It is better to answer something than nothing 😉

NOTE : I do not promote cheating in exams😅 I myself never cheated in any of my exams 😂


Quiz

Congratulations 🎉 ! You have almost reached the end of the article and you are a better developer than you were before reading this article.

Congratulation on that, hope so you understood everything and if so answer the below quiz in the comment section. ( Please write the output in the comment section). Let see who can solve this

carbon.png

Thanks for reading the article in which you learned how to use destructuring for an array. If you still have any doubt on this topic or in any frontend topics do ask your doubts in my DM.

@pitale_shubh

In part 2 we will learn Destructuring for the object data structure. Till then keep learning and improving.