🟢 EasyFunctions📖 Theory Question

What is the spread operator (...) and what are its use cases?

💡

Hint

Expand iterable into individual elements — arrays, function args, object spreading

Full Answer

// 1. Spread in function calls — expand array as arguments
const nums = [1, 5, 3, 2, 4];
Math.max(...nums); // 5 — same as Math.max(1,5,3,2,4)

// 2. Copy and combine arrays (immutable operations)
const a = [1, 2, 3];
const b = [4, 5, 6];
const copy    = [...a];          // [1,2,3] — shallow copy
const merged  = [...a, ...b];    // [1,2,3,4,5,6]
const prepend = [0, ...a];       // [0,1,2,3]

// 3. Spread in object literals (ES2018)
const base = { a: 1, b: 2 };
const extended = { ...base, c: 3 };        // { a:1, b:2, c:3 }
const override = { ...base, b: 99 };       // { a:1, b:99 } — later wins

// 4. Convert iterable to array
const set = new Set([1,2,3]);
[...set]; // [1,2,3]
[...'hello']; // ['h','e','l','l','o']
[...document.querySelectorAll('p')]; // NodeList → Array

// 5. Clone + update (immutable pattern)
const state = { user: 'Alice', count: 0 };
const newState = { ...state, count: state.count + 1 };
💡 Spread creates SHALLOW copies — nested objects are still shared references. Use structuredClone() for deep copies. Spread in objects is order-sensitive: later properties win.

More Functions Questions

🟢 EasyWhat is the difference between call, apply, and bind?→🟢 EasyHow do arrow functions differ from regular functions?→🟢 EasyWhat is a pure function and why does it matter?→🟢 EasyWhat are Higher-Order Functions (HOF)?→

Practice this in a timed sprint →

5 free questions, no signup required

âš¡ Start Sprint