Consider the following sample code
var x = ["a", "b", "c"]; var z = ["p", "q"]; var d = [...x, ...z]; var e = x.concat(z);
Here, the value of d
and e
are exactly same and is equal to ["a", "b", "c", "p", "q"]
, so,
Don't you think the introduction of these little shortcuts in a formal vast language may leave some unnoticed bugs, I mean either it is pretty unnecessary or I do not realize it's need properly.
Spread syntax ( ... ) allows an iterable, such as an array or string, to be expanded in places where zero or more arguments (for function calls) or elements (for array literals) are expected.
The main difference between rest and spread is that the rest operator puts the rest of some specific user-supplied values into a JavaScript array. But the spread syntax expands iterables into individual elements.
We can use the spread operator on iterables like a String or an array and it'll put the contents of the iterable into individual elements. You must have noticed that in the second case (with spread operator), the contents of the greet list were expanded and thrown out of the array.
Syntax: var variablename1 = [... value]; In the above syntax, … is spread operator which will target all values in particular variable.
.concat
is significantly more efficient: http://jsperf.com/spread-into-array-vs-concat because ...
(spread) is merely syntax sugar on top of more fundamental underlying syntax that explicitly iterates over indexes to expand the array.To expand on #3 above, your use of spread is a somewhat contrived example (albeit one that will likely appear in the wild frequently). Spread is useful when - for example - the entirety of an arguments list should be passed to .call
in the function body.
function myFunc(){ otherFunc.call( myObj, ...args ); }
versus
function myFunc(){ otherFunc.call( myObj, args[0], args[1], args[2], args[3], args[4] ); }
This is another arbitrary example, but it's a little clearer why the spread operator will be nice to use in some otherwise verbose and clunky situations.
As @loganfsmyth points out:
Spread also works on arbitrary iterable objects which means it not only works on
Array
s but alsoMap
andSet
among others.
This is a great point, and adds to the idea that - while not impossible to achieve in ES5 - the functionality introduced in the spread operator is one of the more useful items in the new syntax.
For the actual underlying syntax for the spread operator in this particular context (since ...
can also be a "rest" parameter), see the specification. "more fundamental underlying syntax that explicitly iterates over indexes to expand the array" as I wrote above is enough to get the point across, but the actual definition uses GetValue
and GetIterator
for the variable that follows.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With