Destructuring in JS - Explain In Simplest Language

Destructuring assignment -
it allow to unpack values from - [array] & property from {object},
it simply a shortcut way of accessing or printing values from array and property from object,
1) Array[] Destructuring :
// Normol Way To Access Values from Array and Print it,
const MonthOFYear = ["Jan", "Feb", "Mar", "Apr", "May"];
console.log(MonthOFYear[0]);
console.log(MonthOFYear[1]);
console.log(MonthOFYear[2]);
console.log(MonthOFYear[3]);
console.log(MonthOFYear[4]);
here for just printing each values, we have to type whole (MonthOFYear[0]) to (MonthOFYear[4]) ,
to easily access and print values, now JS provide smart way with help of Array[] Destructuring :
// Destructuring with Array :
const MonthOFYear = ["Jan", "Feb", "Mar", "Apr", "May"];
const [Jan, Feb, Mar, Apr, May] = MonthOFYear;
console.log(Jan);
console.log(Feb);
console.log(Mar);
console.log(Apr);
console.log(May);
now we don't have to write whole console.log(MonthOFYear[0]); but we simply write it values vairable name,
Using Different Variable Names :
and it not necessary to gave same vairable name to Array, we can use different vairable name also
const MonthOFYear = ["Jan", "Feb", "Mar", "Apr", "May"];
const [Fist, Sec, third, fourth, fifth] = MonthOFYear;
console.log(Fist);
console.log(Sec);
console.log(third);
console.log(fourth);
console.log(fifth);
SKIPPING VAIRABLE VALUES :
now you only want to gave vairable name to specific values in array and not each values,
here we simply skip Feb, Apr ,
const MonthOFYear = ["Jan", "Feb", "Mar", "Apr", "May"];
const [Jan, , Mar, , May] = MonthOFYear;
console.log(Jan);
console.log(Mar);
console.log(May);
SWAPPING THE ELEMENTS :
// SWAPPING ELEMENT
let a = 1;
let b = 2;
[a, b] = [b, a];
console.log(a);
console.log(b)
2) Object { } Destructuring :
here also we do same, assigning Object values into separate vairable,
const Bike = {
Brand: "Honda",
Price: 1_000_00,
};
const { Brand, Price } = Bike;
console.log(Brand);
console.log(Price);
Using diffent Keys name :
here, you do not need to use name keys name, you can rename also
assiging new vairble name,
const { Brand: MyBrand, Price: NewPrice } = Bike;
console.log(MyBrand);
console.log(NewPrice);
3) Nested Destructuring
What if there is object inside object, and we also want to access it ?
const Job = {
title: "LockManager",
salary: 20_000,
address: {
city: "Nashik",
Pin: 422101,
},
};
const {
title,
salary,
address: { city, pin },
} = Job;
so what a small explanation blog for your..!
hope this blog help you to understand basic of Destructuring
