Sub topic 10
Passing Arrays as Arguments with Spread
This chapter assumes you can declare and call functions, work with arrays, and read rest parameters (...rest) as covered in the previous chapter. It covers the reverse operation: you have the values in an array and need to pass them to a function as separate arguments.
The Problem Spread Solves
Many functions take separate arguments, but your data often arrives in an array. Math.max is a common example. It expects Math.max(5, 10, 15), not Math.max([5, 10, 15]).
const numbers = [5, 10, 15];
console.log(Math.max(numbers)); // NaN, the array is one argument
console.log(Math.max(...numbers)); // 15The ... before numbers is spread syntax. In a function call, it takes an iterable and expands it into separate arguments, in order. The call Math.max(...numbers) behaves exactly like Math.max(5, 10, 15).
Spread Versus Rest: Same Dots, Opposite Jobs
The same three dots mean different things depending on where they appear.
| Location | Name | What it does |
|---|---|---|
| Parameter list: `function f(...args)` | Rest parameter | Gathers several arguments into one array |
| Call site: `f(...arr)` | Spread argument | Expands one iterable into several arguments |
They often appear together. A rest parameter collects whatever spread delivers:
function sum(first, ...rest) {
return rest.reduce((total, n) => total + n, first);
}
const numbers = [5, 10, 15];
console.log(sum(...numbers)); // 30: first = 5, rest = [10, 15]Spread does not change how binding works. After expansion, the usual rules from earlier chapters still apply. Arguments bind to parameters by position, missing ones become undefined, and extra ones are ignored unless a rest parameter collects them.
function describe(a, b) {
return `a=${a}, b=${b}`;
}
console.log(describe(...[1])); // "a=1, b=undefined"
console.log(describe(...[1, 2, 3])); // "a=1, b=2"Mixing Spread with Ordinary Arguments
You can place a spread anywhere in the argument list and use more than one. Each spread expands where it sits.
function log(...items) {
return items.join(" | ");
}
const head = ["a", "b"];
const tail = ["y", "z"];
console.log(log("start", ...head, "middle", ...tail, "end"));
// "start | a | b | middle | y | z | end"A rest parameter, by contrast, must come last in a parameter list. Spread has no such restriction because it runs at the call site, where the full list of values is already known.
Spread Works on Any Iterable
Spread uses the iteration protocol, the same one for...of uses. Any iterable works: arrays, strings, Set, Map, generator results, and arguments.
function show(...parts) {
return parts;
}
console.log(show(..."hi")); // ["h", "i"]
console.log(show(...new Set([1, 1, 2]))); // [1, 2]
console.log(show(...new Map([["k", 1]]))); // [["k", 1]]
function* count() {
yield 1;
yield 2;
}
console.log(show(...count())); // [1, 2]Because spread iterates, a string spreads by code point. Emoji and other characters outside the Basic Multilingual Plane stay whole. "😀".length is 2, but show(..."😀") returns one element.
Non-iterables throw
A plain object is not iterable, so spreading it into a call throws. The same goes for null and undefined.
function f(...args) {
return args;
}
try {
f(...{ a: 1 });
} catch (err) {
console.log(err instanceof TypeError); // true
}
try {
f(...undefined);
} catch (err) {
console.log(err instanceof TypeError); // true
}Spread and Default Values
Array holes and explicit undefined elements spread as undefined, so they trigger default parameters:
function point(x = 0, y = 0) {
return `(${x}, ${y})`;
}
console.log(point(...[5])); // "(5, 0)"
console.log(point(...[undefined, 3])); // "(0, 3)"
console.log(point(...[, 7])); // "(0, 7)", the hole becomes undefined
console.log(point(...[null, 7])); // "(null, 7)", null is passed throughThis follows the rule from earlier chapters: only undefined triggers a default, and spread does not change that.
Spread Replaces apply
Before ES2015, the only way to call a function with an array of arguments was Function.prototype.apply:
const numbers = [5, 10, 15];
console.log(Math.max.apply(null, numbers)); // 15, the old way
console.log(Math.max(...numbers)); // 15, the modern waySpread is shorter and lets you mix in other arguments. It also works with new, which apply cannot do directly:
const parts = [2026, 10, 25]; // month index 10 is November
const date = new Date(...parts);
console.log(date.getFullYear(), date.getMonth(), date.getDate()); // 2026 10 25When the method needs a particular this, call it as a method so this is kept: obj.method(...args). You need apply only if you want to set this and pass the array in one step, and fn.call(thisValue, ...args) covers that case too.
Edge Cases and Common Errors
Empty arrays
Spreading an empty array passes no arguments. That matters for functions whose result with no arguments is surprising:
console.log(Math.max(...[])); // -Infinity
console.log(Math.min(...[])); // InfinityCheck array.length before relying on the result.
Very large arrays
Every spread element becomes a real argument, and engines cap how many arguments a call can take. Spreading hundreds of thousands of elements can throw a RangeError. The exact limit depends on the engine. For large or unbounded data, use a loop or reduce:
const big = Array.from({ length: 1_000_000 }, (_, i) => i);
const max = big.reduce((m, n) => (n > m ? n : m), -Infinity);
console.log(max); // 999999The same concern applies to arr.push(...other) when other is very large.
Forgetting the dots
The most common mistake is passing the array itself. Some functions fail loudly, but many fail quietly. Math.max([1, 2]) returns NaN, and a function with a rest parameter will receive [[1, 2]], an array nested inside an array, with no error at all.
function total(...nums) {
return nums.length;
}
console.log(total([1, 2, 3])); // 1, a single array argument
console.log(total(...[1, 2, 3])); // 3Spread copies nothing deeply
Spread passes the elements themselves. If an element is an object, the function receives a reference to that same object, so changes to its properties are visible to the caller. The chapter on passing primitives and objects covers this rule in full.
Exercise
What does each line log, and why? function f(a, b = "B", ...c) { return [a, b, c]; } then console.log(f(...["x"]));, console.log(f(...["x", undefined, 1, 2]));, and console.log(f(..."hey"));
Show answer
The first logs ["x", "B", []]: only a gets a value, b is undefined so its default applies, and c collects nothing. The second logs ["x", "B", [1, 2]]: the explicit undefined still triggers the default, and the remaining values go into c. The third logs ["h", "e", ["y"]]: the string is iterable, so it spreads into its characters.
Exercise
A teammate writes function latest(dates) { return new Date(Math.max(...dates)); } and calls it with latest(undefined) when no data exists, with an array of 500,000 timestamps, and with an empty array. What happens in each case, and how would you fix the function?
Show answer
latest(undefined) throws a TypeError because undefined is not iterable. The 500,000-element array may throw a RangeError, since that many arguments can exceed the engine's limit. The empty array makes Math.max() return -Infinity, which produces an Invalid Date. A fix: function latest(dates = []) { if (dates.length === 0) return null; return new Date(dates.reduce((m, d) => (d > m ? d : m), -Infinity)); }. The default covers undefined, the guard clause covers the empty case, and reduce avoids the argument limit.
Exercise
Rewrite fn.apply(null, [first].concat(middle, [last])) using spread syntax.
Show answer
fn(first, ...middle, last). Spread can appear anywhere in the argument list, so the concatenation is unnecessary. This assumes middle is an array. Unlike concat, spread would throw if middle were not iterable.