If someone can explain me about how to use spread
, when to use spread
with example would be great.

- 5,792
- 2
- 28
- 41
-
First of all, [there is no such thing as a "spread operator"](https://stackoverflow.com/questions/37151966/what-is-spreadelement-in-ecmascript-documentation-is-it-the-same-as-spread-oper/37152508#37152508) – Felix Kling Jun 26 '18 at 11:59
-
Hi, what we call it – Amruth Jun 26 '18 at 11:59
-
1Have a look at the link. `...` is not one thing, just like `(` or `{` don't have a single meaning/purpose. What they mean depends on the context they are used in. They are part of other syntaxes (array literals, function calls, etc). Look at the documentation for those constructs. Your question is similar to: "Explain how to use `()`", which doesn't make much sense. – Felix Kling Jun 26 '18 at 12:00
-
https://stackoverflow.com/questions/44934828/is-foo-an-operator-or-syntax – Sergio Tulentsev Jun 26 '18 at 12:00
1 Answers
The spread operator
(to not be confused with rest parameters
) acts similarly to apply()
.
It lets you invoke a function passing the arguments of an array as single value instead.
Take for example:
var myArray = [5, 10, 50];
Math.max(myArray); // Error: NaN
Math.max.apply(Math, myArray);
The Math.max()
method doesn’t support arrays; it accepts only numbers. When an array is passed to the Math.max() function, it throws an error. But when the apply() method is used, the array is sent as individual numbers, so the Math.max() method can handle it.
With the spread operator you no longer need to use the apply()
method and you can easily expand an expression into multiple arguments:
var myArray = [5, 10, 50];
Math.max(...myArray); // 50
Easier to write, easier to read.
what are the different ways to use spread(…) in Ecma 6?
Useful for:
1. Combining arrays
var arr1 = [1, 2, 3]; var arr2 = [4, 5, 6];
arr1.push(...arr2)
2. Copying Arrays
Instead of using slice()
var arr1 = [1, 2, 3, 4, 5, 6];
var a = arr1.slice();
you could:
var a = [...arr1]
3. Calling Functions instead of using the apply()
.. as show above.

- 936
- 2
- 9
- 24
-
Please don't call it spread *operator*. It's not an operator. Also point 1 and 3 are the same. – Felix Kling Jun 26 '18 at 16:40
-
Agree. I read your answer a while ago. Ref: "The lack of an official name might be the reason why people started to use "spread operator". I would probably call it "spread argument." True. – leonardofed Jun 26 '18 at 16:45