Destructuring in JavaScript
When JavaScript provides us with the incredible functionality of wrapping data in objects and arrays, we developers don't shy away from using it. Whether it's exporting in modules, returning from functions or even over the network, objects and arrays are used all the time. However, as we pack the data into an entity, someone would need to unpack it too. Let's look at an example:
const user= getUser();
//returns object like: {username:'...',email:'...',password:'...'}
Now, to use this data, we would have to do:
if(user.username)
console.log(user.username);
if(user.email)
console.log(user.email);
if(user.password)
console.log(user.password);
We all know that the username, email and password fields are part of the user, yet we have to maintain the redundancy of writing 'user.' This is a real problem, and the solution to it is pretty elegant. What if we extract the fields from the object instead of using them from the object? Yes, and this extraction is called:
Destructuring
Destructuring is a JavaScript syntax that helps us to unpack values from arrays or properties from objects into distinct variables. This feature allows us to perform many powerful operations, including value swaps, assigning new names to variables and many more.
Destructuring an Array
An array element can be destructured using the following syntax:
const countArray = [1,2,3];
const [a,b,c]=countArray;
console.log(a);
//1
console.log(b);
//2
..
We can also use this with rest operators to get more power during destructuring:
const countArray = [1,2,3,4,5,6,7,8,9];
const [a,b,...rest]=countArray;
const[start,,end]=countArray;
console.log(a);
//1
console.log(b);
//2
console.log(rest);
// [3,4,5,6,7,8,9]
console.log(start);
//1
console.log(end);
//9
If an array element does not have any value, it returns undefined. In such a case, we can pass in default values:
const arr = [1,2];
const [a,b,c]=arr;
//Here a,b=1,2 but c is undefined but we can do :
const [k,l,n=0]=arr;
//Here k and l will be 1 and 2 and n will be 0 by default
We can also use this to swap numbers. Basically, it would be a reassignment.
const a=10;
const b=20;
[a,b]=[b,a];
//Now a=20,b=10
In case fewer variables are given during destructuring, the others will be ignored. The user can choose to take the rest of the elements in another array of nested arrays.
const arr = [1,2,3,4,5,6];
const [a,b]=arr;
//a=1,b=2 rest are ignored
const [a,b,[c,[d,e],f] = arr;
//All values are as it is
const [a,b,...{length}]= arr;
//has the length of the remaining data (here:4) in the last value
Destructuring Objects
Even tho destructuring is pretty popular with arrays, and there are even more use cases of array destructuring, destructuring objects is the most common use case of this JavaScript Syntax. The important thing to remember while destructuring objects is that we need to use the same names as the properties. This is because JavaScript Object properties are not ordered internally. Let us look at the syntax.
const user = {name:'Parikar',email:'pag@gmail.com',pass:'123'}
const {name,email,pass} = user;
console.log(name);
//Parikar
console.log(email);
//pag@gmail.com
console.log(pass);
//Don't console log passwords bro!!
Finally, we can have our properties without the annoying 'user.' But that is not all. Here, too, we can use the rest operator or choose to ignore values or apply default values.
const obj = {a:1,b:2,c:3,d:4};
const {a,b,...rest} = obj;
//a=1,b=2 ,rest ={c:3,b:4}
const {a,b}=obj;
// a=1,b=2 ignores rest of the fields
const {a,b,c,d,e}= obj;
// e is undefined
const {a=0,b=0,c=0,d=0,e=0} = obj;
//code a,b,c,d recieve 1,2,3,4 but e becomes 0 (given default)
Another important property is renaming.
const obj = {a:1,b:2};
const {a:a1,b:b1}= obj;
console.log(a1);
//1
console.log(b1);
//2
Here we got the values by field names, but chose to rename them to a1 and b1.
But what if we don't know the names of the fields?
In arrays, we could name the variables, and the values would be received into them because of the order. But here, if we want to get the object values, it becomes imperative to know the property names...Or does it?
Remember when we had to get the values from an object from a variable key.
//Instead of doing:
Obj.key;
//We Did:
Obj[key];
// key= 'property_name'
Similarly, here we can do:
const user = {name:'parikar',age:21};
const key = 'name';
const {[key]:username} = user;
Here, the value will be extracted in the [key] and put inside a new variable - username.
We can also destructure nested objects like:
const obj = {a:10,b:{c:20};
const {a,b:{c}} = obj;
//a = 10 and c = 20 [b is not bound]
By using the destructuring syntax, we can avoid a lot of repetitive code, and it helps us to focus on the variables we need to work with rather than which object has which property. It is a fairly simple concept to grasp, and with a little practice, you will be using it daily in no time.