...spread and ...rest
A Spread syntax allows in-place expansion of an expression for the following cases:
Array
Function call
Multiple variable destructuring
Rest parameters works in the opposite direction of the spread syntax, it collects an indefinite number of comma separated expressions into an array.
Spread Syntax
Spread example:
Functions aren't the only place in JavaScript that makes use of comma separated lists - arrays can now be concatenated with ease:
Similarly, object literals can do the same thing:
Rest parameter
Rest parameters share the ellipsis like syntax of spread syntax but are used for a different purpose. Rest parameters are used to access indefinite number of arguments passed to a function. For example:
Technically JavaScript already had an arguments
variable set on each function (except for arrow functions), however arguments
has a lot of issues, one of which is the fact that it is not technically an array.
Rest parameters are in fact arrays which provides access to methods like map, filter, reduce and more
. The other important difference is that rest parameters only include arguments not specifically named in a function like so:
Note: Commonly spread syntax and rest parameters are referenced as Spread and Rest operators but they aren't operators according to ECMAScript specifications. Few references MDN-Spread Syntax, MDN-Rest Parameters, ECMAScript Spec - Spread Syntax, ECMAScript Spec - Rest Parameters
Last updated