Skip to main content

spread when calling a function

The spread (...) operator, when calling a function, unpacks (spreads) an array (or another iterable object) into separate arguments of the function.


Syntax:

javascript
myFunc(...array)

is equivalent to

javascript
myFunc(array[0], array[1], array[2], ...)

Example:

javascript
function sum(a, b, c) { return a + b + c; } const numbers = [1, 2, 3]; // spread unpacks the array into separate arguments console.log(sum(...numbers)); // 6

Without spread it would look like this:

javascript
sum(numbers); // NaN - because the function expects three numbers, not one array

Can be used with any iterable structures:

For example, with strings:

javascript
function logChars(a, b, c) { console.log(a, b, c); } logChars(...'abc'); // a b c

Combining spread and regular arguments:

javascript
function greet(greeting, name, punctuation) { console.log(`${greeting}, ${name}${punctuation}`); } const data = ['Hello', 'Bob']; greet(...data, '!'); // Hello, Bob!

Difference between spread and rest:

SyntaxWhere it is usedWhat it does
... (spread)when calling a function or creating an array/objectunpacks an array/object
... (rest)in a function's definitioncollects arguments into an array

Example:

javascript
function showArgs(...args) { // rest collects console.log(args); } const nums = [1, 2, 3]; showArgs(...nums); // spread unpacks -> [1, 2, 3]

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.