Destructuring is a JavaScript expression that lets you unpack values from arrays and properties from objects (and other iterables) into distinct variables. It makes code shorter, more readable, and easier to maintain.
Map via iteration).{ } and matches property names.[ ] and matches by position.Map destructuring is often used inside for...of loops.Array destructuring assigns based on index positions:
Pattern
const [a, b, c] = someArray;
a gets index 0, b gets index 1, etc.const [, second] = arr;Object destructuring assigns based on matching property names:
Pattern
const { prop1, prop2 } = someObject;
const { x = 0 } = obj;
const colors = ["red", "green", "blue"];
const [first, second, third] = colors;
console.log(first); // "red"
console.log(second); // "green"
console.log(third); // "blue"
const person = {
name: "Alice",
age: 25,
country: "USA"
};
const { name, age } = person;
console.log(name); // "Alice"
console.log(age); // 25
const { name: userName, age: userAge } = person;
console.log(userName); // "Alice"
console.log(userAge); // 25
const employee = {
id: 101,
profile: {
fullName: "John Doe",
dept: "Engineering"
}
};
const {
profile: { fullName, dept }
} = employee;
console.log(fullName); // "John Doe"
console.log(dept); // "Engineering"
const map = new Map();
map.set("fruit", "apple");
map.set("color", "red");
for (const [key, value] of map) {
console.log(`${key} => ${value}`);
}
// Output:
// fruit => apple
// color => red
[first, second, third] becomes "red", "green", and "blue" based on positions in the colors array.{ name, age } pulls out the name and age properties from person, so you log "Alice" and 25.name: userName means the name property is stored in a variable called userName.employee.profile and directly get fullName and dept.[key, value], which is destructured into the variables key and value.useState in React).Map entries and directly accessing keys and values.undefined:const { age = 18 } = user;const [, second] = numbers;for...of loops, where each entry is [key, value].null or undefined – it will throw a runtime error. Check or use safe defaults first.const { fullName: employeeName } = employee.profile;firstFruit and secondFruit.book with properties like title, author, and year. Destructure these inside a function parameter and log them.Map of country–capital pairs and use a for...of loop with destructuring to print them as Country: Capital.student.profile.contact.email) and use nested destructuring to extract email in one statement.role = "guest").