Day 2 · Concept 06
Destructuring & spread
const {a, b} = obj pulls fields out. const [x, y] = arr does it for arrays. ... spreads or collects. Together they replace half the boilerplate you'd write in older languages.
1 · Object destructuring
const user = { name: "Alice", age: 30, role: "admin" };
// Basic
const { name, age } = user;
console.log(name, age);
// Rename
const { name: n, age: a } = user;
console.log(n, a);
// Default
const { city = "unknown" } = user;
console.log(city);
// Nested
const data = { user: { profile: { handle: "alice" } } };
const { user: { profile: { handle } } } = data;
console.log(handle);2 · Array destructuring
const [first, second, ...rest] = [10, 20, 30, 40, 50];
console.log(first, second, rest); // 10 20 [30, 40, 50]
// Swap
let a = 1, b = 2;
[a, b] = [b, a];
console.log(a, b); // 2 1
// Skip
const [, , third] = [1, 2, 3];
console.log(third); // 33 · Destructuring in function signatures
// Before — many positional args
function createUser(name, age, role, country) { /* ... */ }
// After — named params via destructuring
function createUser({ name, age, role = "user", country = "US" }) {
return `${name} (${age}, ${role}, ${country})`;
}
console.log(createUser({ name: "Alice", age: 30 }));Self-documenting calls; default values; can rearrange without breaking callers.
4 · Spread — copy and merge
const a = [1, 2, 3];
const b = [4, 5, 6];
// Concat
console.log([...a, ...b]); // [1, 2, 3, 4, 5, 6]
// Copy (shallow)
const c = [...a];
// Merge objects
const base = { id: 1, name: "Alice" };
const updates = { name: "Bob", role: "admin" };
console.log({ ...base, ...updates }); // later keys winOrder matters.
{...a, ...b} — keys in b
override keys in a. Useful for defaults: {...defaults, ...userOpts}.5 · Rest — the gather pattern
// Function rest
function avg(...nums) {
return nums.reduce((a, b) => a + b, 0) / nums.length;
}
console.log(avg(1, 2, 3, 4, 5)); // 3
// Object rest
const { id, ...withoutId } = { id: 1, name: "Alice", age: 30 };
console.log(withoutId); // { name: 'Alice', age: 30 }6 · Common mistakes
- Shallow copy only.
{...obj}copies the top level. Nested objects share references. - Destructuring undefined.
const {a} = undefinedthrows. Default the source:const {a} = obj || {}. - Renaming syntax confusion.
const {a: b} = objmeans "takea, call itb". Not "takeb".
7 · When it clicks
- You destructure in every function signature with more than 2 params.
...spreadis your default for "copy this object with one change".- You never write
function(opts)+opts.xanymore.
Found this useful?