How Destructuring works in JavaScript- A simple yet detailed guide - Part 1 (Destructuring Arrays).
This article talks about a very crucial but underrated topic which is Destructuring. You will learn what is destructuring and how does it works in JS.
This article will be divided into 3 parts:
What is Destructuring ?
Why do we need Destructuring?
How to master Destructuring so that we can easily play with JavaScript objects and arrays.
What is Destructuring?
Destructuring is a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables.
- freecodecamp
Umm. it is quite a descriptive and self-explanatory definition but to structure it in layman's terms, Destructuring is breaking a complex Data structure(arrays, objects..) into a simpler data structure that is primitives (variables).
- Gyani Priyansh.
So, I hope this clears you up on what is Destructuring and also setup some excitement to learning it as isn't it what we all want? To break down every complex thing around us in a much simpler or more understandable or easy-to-work-with stuff.
Why do we need Destructuring?
A very good question indeed, and the answer is quite simple 'Just because it reduces a lot of overhead and does the task in very less lines of code which is more readable and maintainable'. Although it doesn't create much of a performance difference it's always a good practice to assign data to a variable rather than assessing it using arrays or objects every time you need to access it.
Just to give you a quick example:
What would you prefer - 1. Declaring a variable 'btn' for a button at the start of your js file as you might going to use it a lot of times.
const btn = document.getElementById('btn);
- Using "document.getElementById('btn);" every time you wanna access that button.
If you choose 2nd option. God Bless you! Although the performance difference is not at all considerable (or there might be no difference at all) but still 90% of developers will prefer 1st option as it is much cleaner and will be quite easy to modify once you need to change the 'id' of that button.
I hope you are now convinced that Destructuring can really be a crucial tool and you should learn it but for people who are still sceptical about it there is a very simple yet powerful example for you all below:
// task : You want to store these value somewhere as it might be useful afterwards
const starterMenu = ["Pasta", "Chicken Chilly", "Panner Chilly", "Fries"];
//Method 1
const sMenu1 = starterMenu[0];
const sMenu2 = starterMenu[1];
const sMenu3 = starterMenu[2];
const sMenu4 = starterMenu[3];
//Method 2
const [sMenu1, sMenu2, sMenu3, sMenu4] = starterMenu;
Don't judge me by this example I know it doesn't make a lot of sense but still, the questions remain the same, it might not be the best example to explain it but you can see for yourself how massive a difference can 'Destructuring' create while performing Data extraction or Data unpacking tasks.
Now, let's proceed further and master this concept.
How to master Destructuring in JavaScript.
To master Destructuring we have to understand what all Data Structures can be implemented. To my knowledge, we will mostly be implementing Destructuring in 2 Data Structures that is: Objects and Arrays. So, we will discuss these 2 only. In this article, I will focus only on Destructuring Arrays.
From now on, I will explain all the concepts taking an example of a Restaurant and creating a restaurant object.
//Example Object
const restaurant = {
name: "Box 9",
yearOfestablishment: 1999,
city: "Hyderabad",
categories: ["Chinese", "Italian", "India"],
starterMenu: ["Pasta", "Chicken Chilly", "Panner Chilly", "Fries"],
mainMenu: ["Risotto", "Thali", "Biryani", "Fried Rice"],
};
Destructuring Arrays
As it is already established that Destructuring is used to simplify the Data extraction or Data unpacking from a Data structure and storing them into variables or other simple data structures.
Destructuring of Arrays is quite simple as well as very intuitive. Let me explain how and also explain some of the keynotes:
Syntax: The syntax for Destructuring Arrays is very simple as it is the "[]" the array syntax itself but the only difference is that you put "[]" left-hand side of equals to "=" so that the JavaScript engine can understand that this is not an Array declaration but a Destructuring operation. For ex:
const [x,y] = [3,5];
This will simply assign 3 to x and 5 to y but to make these variables available to be modified afterwards you let instead of const.
Note: Although destructuring sounds like a destructive approach it is not at all destructive instead it is a very simple, calm and cute approach as it does not affect the original data structure at all.
Assigning Values: As you, sharp mind guys have already noticed that we are till now unpacking all the values from an Array and you might have thought that this is how it works but you are wrong again! Puff🤦
We can unpack any number of values we want or we need unless and until we are maintaining the order. Let me explain with an example of our Resatraunt code :
const restaurant = {
name: "Box 9",
yearOfestablishment: 1999,
city: "Hyderabad",
categories: ["Chinese", "Italian", "India"],
starterMenu: ["Pasta", "Chicken Chilly", "Panner Chilly", "Fries"],
mainMenu: ["Risotto", "Thali", "Biryani", "Fried Rice"],
order(starterIndex , mainIndex){
return [this.starterMenu[starterIndex], this.mainMenu[mainIndex]];
};
const [sMenu1 , , sMenu2] = restaurant.starterMenu;
In this example, we only grab 1st and 3rd value and ignore every other value. We did this by creating a hole* in our Destructuring operator stating we only want values from 1st and 3rd place.
Tricks with Destructuring:
Swapping two variables -
let x = 5; let y = 10; // Normal Swapping let temp = x; x=y; y=temp; //Swapping using Destructuring [x,y] = [y,x];
Crazy isn't it!!!
We can immediately destructure an array returned by a function. Ex: Assume someone orders something from the restaurant say 'starter and main course we can get that data and immediately unpack it to get the value from it.
const [starter , main] = restaurant.order(2,1);
Nested Arrays: We can unpack even nested arrays using Destructure that too quite easily. Ex:
const nestedArr = [2,6,[5,9]]; const [x,,y] = nestedArr; console.log(x , y ) ==> 2 [5,9] //Unpacking nested array const [x,,[y,z]] = nestedArr; console.log(x , y , z) ==> 2 5 9
Note: If you are afraid that you are unpacking more values than it is there in an array (as the length of the array is unknown, it is common in the case of data fetch from APIs) so you can also define a default value:
const arr = [data1 , data2];
const [x=1, y=1 ,z=1] = arr;
console.log(x,y,z) ==> data1 data2 1
I hope I have explained it well for you to understand and implement Destructuring in Arrays. I feel that the article is already quite lengthy so I will stop it here and will discuss Object Destructuring in Part 2 of it.
If you read this all through and you are here, I can't appreciate you enough and I hope that it does add some value in terms of how you see Destructuring incase you are introduced to this concept through this article I hope it makes you more curious about it and you will study it further.
Resources:
Jonas Schmedtmann Udemy couse.
MDN and Freecode camp blogs.
hole*\= It is nothing but a space we left for a specific value if we do not want to unpack it.