Destructuring is a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables. It makes your code much cleaner and easier to read.
You can extract properties from an object directly into variables with the same name.
const person = { name: "Mim", age: 22, city: "Dhaka" };
// Destructuring
const { name, age } = person;
console.log(name); // Mim
console.log(age); // 22
You can also rename the variables during destructuring:
const { name: fullName, age: yearsOld } = person;
console.log(fullName); // Mim
When destructuring arrays, the order is important. Values are assigned based on their position (index).
const fruits = ["Apple", "Banana", "Cherry"];
// Unpacking values
const [first, second] = fruits;
console.log(first); // Apple
console.log(second); // Banana
A variable can be assigned a default value, in the case that the value
unpacked from the object or array is undefined.
const person = { name: " Mim" };
const { name, country = "Bangladesh" } = person;
console.log(country); // Bangladesh
Destructuring is extremely useful for handling object parameters in functions, making the required data very explicit.
function printUser({ name, age }) {
console.log(`${name} is ${age} years old.`);
}
const user = { name: "Mim", age: 22, color: "Blue" };
printUser(user);
undefined results