Destructuring in JavaScript
Destructuring is a concise way to unpack values from arrays or properties from objects into distinct variables.
📦 Array Destructuring
const numbers = [1, 2, 3];
const [a, b, c] = numbers;
console.log(a); // 1
console.log(b); // 2
You can skip values by leaving gaps:
const [first, , third] = [10, 20, 30];
console.log(third); // 30
📁 Object Destructuring
const user = { name: "Alice", age: 25 };
const { name, age } = user;
console.log(name); // Alice
console.log(age); // 25
Rename variables using a colon:
const { name: userName } = user;
console.log(userName); // Alice
🧠 Default Values
const { city = "Unknown" } = user;
console.log(city); // Unknown
🔄 Swapping Values with Destructuring
let x = 1, y = 2;
[x, y] = [y, x];
console.log(x); // 2
console.log(y); // 1
📌 Destructuring in Function Parameters
function greet({ name, age }) {
console.log(`Hello ${name}, age ${age}`);
}
greet({ name: "Bob", age: 30 });
💡 Tip: Destructuring makes your code cleaner, especially in functions and loops.