Homework Assignment #16: Rest and Spread
What are the differences between rest and spread?
-
JavaScript ECMA6 came with cool new features '...' , is new JavaScript functionalists.
It can be used in two different ways; as a spread operator OR as a rest parameter.
-
Rest parameter: collects all remaining elements into an array.
-
Spread operator: allows iterables( arrays / objects / strings ) to be expanded into
single arguments/elements.
Rest parameters
From the definition we saw earlier, rest parameters collect all the remaining
elements into an array.
Code Editor & preview
Note: Rest parameters have to be at the last argument.
This is because it collects all remaining/ excess arguments into an array.
Spread Operators
Spread operator helps us to expand the strings or array literals or object literals.
Code Editor & preview
Summary :
-
When we see "..." in the code, it is either rest parameters or the spread operator.
- There’s an easy way to distinguish between them:
-
When ... is at the end of function parameters, it’s “rest parameters” and
gathers the rest of the list of arguments into an array.
When ... occurs in a function call or alike, it’s called a “spread operator” and
expands an array into a list.
-
Use patterns:
-
Rest parameters are used to create functions that accept any number of arguments.
The spread operator is used to pass an array to functions that normally require a
list of many arguments.
Together they help to travel between a list and an array of parameters with ease.
- All arguments of a function call are also available in “old-style” arguments: array-like iterable object.