Destructuring
Object and array destructuring patterns
// Object destructuring with rename, defaults, and rest
const user = { name: "Alice", age: 30, city: "NYC" };
const { name: userName, age, country = "USA", ...rest } = user;
console.log(userName, age, country, rest);
// Array destructuring with skip and rest
const [first, , third, ...others] = [1, 2, 3, 4, 5, 6];
console.log(first, third, others);
// Nested destructuring with safe default
const response = { data: { user: { id: 42 } } };
const { data: { user: { id, role = "guest" } = {} } = {} } = response;
console.log(id, role);
// Function parameter destructuring
function formatUser({ name, age = 0, admin = false }) {
return `${name} (${age}) ${admin ? "[admin]" : ""}`;
}
console.log(formatUser({ name: "Bob", admin: true }));