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)); // 6Without spread it would look like this:
javascript
sum(numbers); // NaN - because the function expects three numbers, not one arrayCan 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 cCombining 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:
| Syntax | Where it is used | What it does |
|---|---|---|
... (spread) | when calling a function or creating an array/object | unpacks an array/object |
... (rest) | in a function's definition | collects 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 readyPremium
A concise answer to help you respond confidently on this topic during an interview.