Sub topic 7
Spreading Arrays into Literals and Calls
This chapter assumes you can declare variables with let and const, work with arrays, write and call functions, and tell a primitive value from a reference. It also builds on the previous chapter on rest parameters. Rest collects separate arguments into one array. Spread does the reverse: it expands one array into separate values.
The two use the same ... token. Which one you get depends on where the token appears:
| Position of `...` | Name | Effect |
|---|---|---|
| In a function's parameter list | Rest parameter | Collects arguments into an array |
| Inside a destructuring pattern | Rest element | Collects remaining items into an array |
| Inside an array literal `[ ]` | Array spread | Expands items into the new array |
| Inside a call's argument list `f( )` | Argument spread | Expands items into separate arguments |
A simple rule covers every case. On the receiving side (parameters, patterns), ... collects. On the producing side (literals, calls), ... expands.
Spread in Array Literals
Inside an array literal, ...expr takes each element of expr and inserts it at that point, in order. You can mix spread elements with ordinary elements and use as many spreads as you like.
const values = [3, 9, 4];
const more = [7, 8];
console.log([0, ...values, 10]); // [0, 3, 9, 4, 10]
console.log([...values, ...more]); // [3, 9, 4, 7, 8]
console.log([...more, 5, ...values]); // [7, 8, 5, 3, 9, 4]The engine builds the result from left to right. It evaluates each element and appends plain values directly. Spread elements are iterated one item at a time, and each item is appended.
Copying an array
[...arr] creates a new array that holds the same elements. The new array has its own identity, so you can push to it or sort it without changing the original.
const original = [3, 1, 2];
const copy = [...original];
copy.sort();
console.log(original); // [3, 1, 2]
console.log(copy); // [1, 2, 3]
console.log(copy === original); // falseThis is the standard way to avoid methods that change an array in place. sort, reverse and splice all modify the array they are called on, so copy first: [...items].reverse().
Inserting and concatenating
Spread lets you build an array with an item added at the start, end, or middle, without changing the source:
const letters = ['a', 'b', 'd', 'e'];
const index = 2;
const prepended = ['z', ...letters];
const appended = [...letters, 'f'];
const inserted = [...letters.slice(0, index), 'c', ...letters.slice(index)];
console.log(prepended); // ['z', 'a', 'b', 'd', 'e']
console.log(appended); // ['a', 'b', 'd', 'e', 'f']
console.log(inserted); // ['a', 'b', 'c', 'd', 'e']
console.log(letters); // ['a', 'b', 'd', 'e'] (unchanged)Spread compared with `concat`
a.concat(b) and [...a, ...b] usually give the same result, but they work differently:
| Aspect | `[...a, ...b]` | `a.concat(b)` |
|---|---|---|
| What it accepts | Any iterable | Arrays are flattened one level; other values are appended as single items |
| Non-array argument | `[...a, ...5]` throws `TypeError` | `a.concat(5)` appends `5` |
| A string argument | `[...'hi']` gives `['h', 'i']` | `[].concat('hi')` gives `['hi']` |
| Sparse arrays | Holes become `undefined` | Holes are kept as holes |
| Readability for mixed items | `[x, ...a, y]` reads in order | Needs chaining |
const a = [1, 2];
console.log(a.concat(3, [4, 5])); // [1, 2, 3, 4, 5]
console.log([...a, 3, ...[4, 5]]); // [1, 2, 3, 4, 5]
console.log([].concat('hi')); // ['hi']
console.log([...'hi']); // ['h', 'i']Use spread when you know the inputs are arrays or other iterables. Use concat when an input may be either a single value or an array and you want both handled.
Spread in Function Calls
Inside an argument list, ...expr passes each element of expr as its own argument. This replaces the older Function.prototype.apply idiom.
const values = [3, 9, 4];
// Old style
console.log(Math.max.apply(null, values)); // 9
// Spread
console.log(Math.max(...values)); // 9
console.log(Math.max(1, ...values, 20)); // 20Spread arguments can appear anywhere in the call, and you can use more than one. They also work with new, which apply could not do directly:
const parts = [2026, 10, 24]; // month index 10 is November
const date = new Date(...parts);
console.log(date.getFullYear(), date.getMonth(), date.getDate()); // 2026 10 24Appending in place with `push`
push accepts any number of arguments, so target.push(...source) appends every element of source to target and modifies it in place:
const target = [1, 2];
const source = [3, 4, 5];
target.push(...source);
console.log(target); // [1, 2, 3, 4, 5]This differs from target = [...target, ...source], which builds a new array. Use push(...) when you own the array and want to change it. Use a new literal when other code holds a reference to the old array and must not see the change.
Spread meets rest
A function with a rest parameter and a call with spread fit together. You can expand an array into separate arguments and the function collects them back into a new array.
function logAll(label, ...items) {
console.log(label, items.length, items);
}
const list = ['x', 'y', 'z'];
logAll('items:', ...list); // items: 3 ['x', 'y', 'z']The items array inside the function is a new array. It is not list.
Edge Cases and Common Errors
Spreading something that is not iterable
Array spread and argument spread both use the iteration protocol. The value must have a Symbol.iterator method. Plain objects, numbers, null and undefined do not have one, so spreading them throws.
const attempts = [
() => [...{ a: 1 }],
() => [...null],
() => Math.max(...undefined),
];
for (const attempt of attempts) {
try {
attempt();
} catch (err) {
console.log(err instanceof TypeError, err.message);
}
}
// true ... is not iterable (exact wording varies by engine)This catches people out when an optional array is missing. Guard with a fallback: [...(maybeList ?? [])].
Array-likes are not iterables
An array-like has a length and numeric keys but no iterator. Spread rejects it, while Array.from accepts it.
const arrayLike = { 0: 'a', 1: 'b', length: 2 };
console.log(Array.from(arrayLike)); // ['a', 'b']
try {
console.log([...arrayLike]);
} catch (err) {
console.log(err instanceof TypeError); // true
}
function f() {
return [...arguments]; // arguments is iterable, so this works
}
console.log(f(1, 2)); // [1, 2]DOM NodeList objects and the arguments object are iterable in modern environments, so spread works on them. When you are unsure, Array.from is the safer choice.
Holes become `undefined`
A sparse array has empty slots. Spread reads each index through the iterator, which reports a hole as undefined, so the copy is dense.
const sparse = [1, , 3];
const dense = [...sparse];
console.log(1 in sparse); // false (a real hole)
console.log(1 in dense); // true (an actual undefined value)
console.log(dense); // [1, undefined, 3]This matters with methods like forEach and map, which skip holes but do visit undefined values.
Empty arrays and `Math.max`
Spreading an empty array passes zero arguments. Some functions handle that in surprising ways:
console.log(Math.max(...[])); // -Infinity
console.log(Math.min(...[])); // InfinityCheck values.length first if an empty input should mean something else.
Very large arrays in calls
Each spread argument becomes a real argument on the call stack. Engines limit how many arguments a call can take. For arrays with hundreds of thousands of elements, Math.max(...huge) or target.push(...huge) can throw a RangeError. The exact limit depends on the engine and the available stack. Array literals do not have this limit, because building [...huge] does not involve a call.
For large or unknown sizes, use a loop or reduce:
const huge = Array.from({ length: 500000 }, (_, i) => i);
const max = huge.reduce((m, n) => (n > m ? n : m), -Infinity);
console.log(max); // 499999Cost
Every spread iterates its source. [...a, ...b] is linear in the total length. Inside a loop, writing result = [...result, item] copies the whole array on each pass, which makes the loop quadratic. If you are building one array locally, push is the better choice.
const items = [1, 2, 3, 4];
// Quadratic: copies result on every iteration
let slow = [];
for (const item of items) slow = [...slow, item * 2];
// Linear: appends in place
const fast = [];
for (const item of items) fast.push(item * 2);
console.log(slow, fast); // [2, 4, 6, 8] [2, 4, 6, 8]Spread also accepts strings, Sets, Maps and generators. The chapter "Beyond Arrays: Strings, Sets, Maps, and Other Iterables" covers them.
Exercise
What does this code print, and why? const a = [1, 2]; const b = [...a, ...a.reverse()]; console.log(a, b);
Show answer
It prints [2, 1] [1, 2, 2, 1]. The literal is evaluated left to right. The first ...a iterates [1, 2] and appends 1 and 2. Then a.reverse() reverses a in place to [2, 1] and returns it, and the second spread appends 2 and 1. Because reverse changed a itself, logging a afterwards shows [2, 1].
Exercise
A function receives scores, which may be an array of numbers or undefined. Write an expression that returns the highest score, or null when there are no scores, without throwing and without returning -Infinity.
Show answer
scores?.length ? Math.max(...scores) : null. Optional chaining gives undefined when scores is missing, and an empty array has length 0, so both cases return null. Spread only runs when at least one score exists, so it cannot throw a TypeError or return -Infinity. For very large arrays, replace Math.max(...scores) with a reduce to avoid the argument-count limit.
Exercise
Why does [...{ 0: 'a', length: 1 }] throw while Array.from({ 0: 'a', length: 1 }) returns ['a']?
Show answer
Array spread needs an iterable, meaning an object with a Symbol.iterator method. A plain object with a length property is only array-like and has no iterator, so spread throws a TypeError. Array.from first checks for an iterator and, when none exists, falls back to reading length and the numeric indexes.