Spread & Rest
Expand or collect values with the ... syntax.
Syntax
[...arr1, ...arr2]
function f(...args) { }The three dots ... have two related uses:
- Spread β expands an array or object into individual items, great for copying or merging.
- Rest β collects multiple values into a single array, often in function parameters.
Example
Loading editorβ¦
Press Run to execute the code.
When to use it
- Merge user-supplied options with defaults when configuring a third-party library.
- Clone an array before sorting it so the original order is not mutated.
- Spread function arguments from an array when calling a function that expects individual parameters.
More examples
Spread to clone and extend an array
Spreads base into a new array and appends extra elements, leaving the original untouched.
const base = [1, 2, 3];
const extended = [...base, 4, 5];
console.log(extended); // [1, 2, 3, 4, 5]
console.log(base); // [1, 2, 3] β unchangedMerge objects with spread
Merges two objects into a new one; later spread properties win if keys collide.
const defaults = { timeout: 3000, retries: 3 };
const overrides = { retries: 5 };
const config = { ...defaults, ...overrides };
console.log(config); // { timeout: 3000, retries: 5 }Spread array as function args
Spreads an array into individual arguments for Math.max, which does not accept an array directly.
const nums = [4, 1, 7, 2, 9];
console.log(Math.max(...nums)); // 9
Discussion