Destructuring in JavaScript

Destructing is JavaScript is way to to extract values from arrays or objects and assign them to variables in a clean syntax.
Destructuring of Arrays
Let's take a example where we need to extract the value from an array.
What would be the first thing comes to our mind ?
It is simple to use indexes like:
const arr = [10, 20, 30];
const a = arr[0];
const b = arr[1];
But this can be written in a far better syntax using destructuring syntax like:
const arr = [ 10, 20, 30 ]
//variable are unpack and assigned at the same time
const [ a, b, c ] = arr
console.log(a) //10
console.log(c) //30
We can also skip values here like:
const arr = [10, 20, 30]
const [first, , third] = arr
console.log(third) //30
Using rest operators
const [first, ...rest] = [1, 2, 3, 4] //Make sure to write rest at the end
console.log(first) //1
console.log(rest) //[2, 3, 4]
Destructuring Objects
Now objects can also be destructured similarly to the arrays. For example:
//First see the Before Case
const name = user.name
const age = user.age
After using destructung syntax:
const user = {
name: "Ram",
age: 21
};
const { name, age } = user;
console.log(name); // Ram
We can also rename the variables like:
const user = {
name: "Ram",
age: 22
};
const { name: userName } = user;
console.log(userName); // Ram
The line const { name: userName } = user is actually equivalent to const userName = user.name. So in a single line we can access any property of the object and assign it to a variable. But remember now the object property name is assigned to userName hence we cannot use name to access user.name field. For example:
console.log(name); // Error
console.log(userName); // Works
console.log(user.name) //Works
Nested Destructuring
Rather writing the below code:
const user = {
name: "Ram",
address: {
city: "Kolkata"
}
};
const address = user.address;
const city = address.city;
We can write something like :
const user = {
name: "Ram",
address: {
city: "Kolkata"
}
};
const { address: { city } } = user; //we have extracted city directly
console.log(city); // Kolkata
console.log(address); // Error //For address keep const {address} = user
Default Values in Destructuring
We can also use the default values for array and objects like:
const [a = 5, b = 10] = [1] //default value get overridden
console.log(a)// 1
console.log(b)// 10
const user = { name: "Bikash" };
const { name, age = 18 } = user; //Here we adding age as variable not mutating the original object
console.log(age); // 18
console.log(user.age) //undefined
NOTE: Default only works when the value of the field is undefined not null
const user = { age: null };
const { age = 18 } = user;
console.log(age); // null
Importance of Destructing
It keeps the code cleaner and maintainable.
Faster development. Two things can be written in a single line.
Used almost every time in real projects.
const {id, email} = req.body //in express const Page = ({user, order}) => {} //As props in React





