JavaScript Lesson 16: Spread and Rest

⚡ JavaScript CourseLesson 16 of 20 · 80% complete

The spread operator (…) and rest parameters share the same syntax but work in opposite ways. Spread expands, rest collects. Both appear constantly in real JavaScript code.

Spread with Arrays

const a = [1, 2, 3];
const b = [4, 5, 6];

// Combine arrays
const combined = [...a, ...b];    // [1,2,3,4,5,6]

// Copy an array (not a reference!)
const copy = [...a];              // [1,2,3]

// Add items
const withNew = [...a, 10, 11];   // [1,2,3,10,11]

// Pass array as function arguments
const nums = [3, 1, 4, 1, 5, 9];
console.log(Math.max(...nums));   // 9

Spread with Objects

const defaults = { theme: "dark", lang: "en", size: 12 };
const custom = { lang: "fr", name: "Alice" };

// Merge objects (later values win)
const config = { ...defaults, ...custom };
console.log(config);
// { theme: "dark", lang: "fr", size: 12, name: "Alice" }

// Copy and update an object
const user = { id: 1, name: "Alice", age: 30 };
const updated = { ...user, age: 31, email: "alice@example.com" };
console.log(updated);
// { id: 1, name: "Alice", age: 31, email: "..." }

Rest Parameters

// Collect all remaining arguments into an array
function sum(...numbers) {
  return numbers.reduce((total, n) => total + n, 0);
}

console.log(sum(1, 2, 3));           // 6
console.log(sum(1, 2, 3, 4, 5));     // 15
console.log(sum(10, 20, 30, 40, 50)); // 150

// Rest in destructuring
const [first, second, ...rest] = [1, 2, 3, 4, 5];
console.log(rest);  // [3, 4, 5]

🏋️ Practice Task

Create a function mergeConfigs(…configs) that takes any number of config objects and merges them left to right (later values override earlier ones). Test with 3 different config objects.

💡 Hint: Use …configs as rest param. Then use configs.reduce((merged, config) => ({…merged, …config}), {})

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *