Destructuring and spread
Destructuring unpacks values from arrays and objects into separate variables in one line.
Array destructuring
JavaScript
const point = [3, 4];
const [x, y] = point;
console.log(x, y);
const [first, , third] = ["a", "b", "c"]; // skip with an empty slot
console.log(first, third);
let a = 1, b = 2;
[a, b] = [b, a]; // swap
console.log(a, b);Object destructuring
Pull out properties by name:
JavaScript
const user = { name: "Asha", age: 21, city: "Mumbai" };
const { name, city } = user;
console.log(name, city);
const { age: years } = user; // rename while unpacking
console.log(years);
const { country = "India" } = user; // default if missing
console.log(country);In function parameters
Destructuring in parameters makes functions self-documenting:
JavaScript
function describe({ name, age, city = "unknown" }) {
return `${name} (${age}) lives in ${city}`;
}
console.log(describe({ name: "Leo", age: 30, city: "London" }));
console.log(describe({ name: "Mei", age: 24 }));Nested destructuring
JavaScript
const order = { id: 101, customer: { name: "Raj", address: { city: "Delhi" } }, items: ["Lamp", "Chair"] };
const { customer: { name, address: { city } }, items: [firstItem] } = order;
console.log(name, city, firstItem);Spread: ...
The spread operator expands an array or object into its parts. It's the standard way to copy and merge:
JavaScript
const a = [1, 2, 3];
const b = [...a, 4, 5]; // copy and extend
console.log(b);
const defaults = { theme: "light", fontSize: 14 };
const prefs = { fontSize: 18 };
const settings = { ...defaults, ...prefs }; // later properties win
console.log(settings);
console.log(Math.max(...a)); // spread into function argumentsRest: the opposite
In destructuring, ... collects the rest:
JavaScript
const [head, ...tail] = [10, 20, 30, 40];
console.log(head, tail);
const { password, ...safeUser } = { name: "Asha", email: "a@x.com", password: "secret" };
console.log(safeUser); // everything except the passwordFinished this lesson?Mark it complete to earn +20 XP and move your progress on.