Spreading Arrays into Function Arguments
You'll learn how to use the spread operator to unpack array elements as individual function arguments.
The Problem
Some functions expect multiple separate arguments rather than a single array. For example, Math.max() wants numbers like Math.max(5, 12, 8), not an array Math.max([5, 12, 8]). Before spread, you'd have to use awkward methods like .apply() to convert your array.
Using Spread with Functions
The spread operator (...) lets you "unpack" an array directly into a function call:
const numbers = [5, 12, 8, 3];
// Without spread - doesn't work as intended
console.log(Math.max(numbers)); // NaN (passes whole array as one arg)
// With spread - expands array into individual arguments
console.log(Math.max(...numbers)); // 12
Think of ...numbers like opening a box and laying out its contents individually. The function receives 5, 12, 8, 3 as separate arguments, not one array.
Mixing Spread with Regular Arguments
You can combine spread arrays with normal arguments:
const scores = [85, 92];
const highest = Math.max(100, ...scores, 78);
console.log(highest); // 100
// Equivalent to: Math.max(100, 85, 92, 78)
Real-World Example
const coordinates = [50, 100];
function drawPoint(x, y) {
console.log(`Drawing at x:${x}, y:${y}`);
}
drawPoint(...coordinates); // "Drawing at x:50, y:100"
Key Takeaway: Use the spread operator (...) to convert array elements into individual function arguments, making it easy to work with functions that expect separate parameters rather than arrays.