Rest and Spread
Many built-in JavaScript functions support an arbitrary number of arguments.
For example:
Math.max (arg1, arg2, ..., argN)
- calculates the maximum number of the passed arguments.
Math.min (arg1, arg2, ..., argN)
- returns the minimum value of the passed arguments.
In this article, we will learn how to do the same with our own functions and how to pass parameters to such functions as an array.
Remaining parameters (... rest)
You can call a function⚙️ with any number of arguments, regardless of how it was defined.
For example :
Extra arguments will not cause an error, but of course only the first three will be counted.
ES6 concept
Starting with the ES6 standard, a concept has appeared like ... rest
- residual parameters.
let goFun = (...rest) => {
// Algorithm
}
Free parameters can be indicated with three dots ...
. It literally means: "collect the remaining parameters and put them in an array."
For example, let's collect all the arguments into an array args
:
The answer is already 28 and no errors! Try changing the arguments or the dimension of the array.
Multiple parameters
We can put the first few parameters in variables , and collect the rest into an array.
This means that you can simply insert ... rest
, but only instead of the last parameter of the function.
let goFun = (first, second, ...rest) => {
// Algorithm
}
In the example below, the first two 2️⃣ arguments to the function will become the first and last name, and the third and subsequent arguments will become the array titles [i]
:
Possible mistakes
Residual parameters must be at the end, so you cannot write anything after them. This will throw an error:
function f(arg1, ...rest, arg2) { // arg2 после ...rest ?
// Mistake!
}
... rest
must always be last.
Spread operator ... spread
We learned how to get an array from a parameter list, but sometimes you need to do the opposite - stuff the array into the called function⚙️.
For example, there is a built-in function ⚙️ Math.max
. It returns the largest number in the list:
Not so simple
Let's say we have an array of numbers [3, 5, 1]
. How to call Math.max
for it?
You can't just insert them - Math.max
expects to get a list of numbers, not a single array.
Of course, we can enter numbers manually: Math.max (arr[0], arr[1], ar[2]).
But, firstly, it looks bad, and, secondly, we do not always know how many arguments there will be. There can be a lot of them, or not at all.
Occurrence of parameters
The ...spread
operator will help us here. It is similar to residual parameters - it also uses ...
, but does the exact opposite.
When the ...spread
functionality is used in a function call, it converts the arr
array object to an argument list.
For Math.max
:
In the same way, we can pass multiple iterables :
Cool! A very flexible approach to programming. You can also combine the spread operator with normal values.
Merging Arrays
The spread operator ... spread
can also be used to merge arrays :
Converting to string
The ... spread
operator functionality works with any iterable object.
For example, the spread operator is suitable for converting a string into an array of characters :
let str = 'Hey, Alex!'
let result = [...str]
Let's see what happens. Under the hood, the spread operator uses iterators to iterate over the elements. Just like for..of
does.
The for..of
loop iterates over the string as a sequence of characters, so from ... str
it turns out "P", "p", "and", "in", "e", "t" ...
The resulting characters are collected into an array using the standard array declaration [... str] .
We can also use Array.from
for this task. It also converts an iterable (such as a string) to an array :
let str = 'Hello'
Array.from(str) // "H", "e", "l", "l", "o"
// Array.from converts an iterable to an array
The result is the same as [...str]
. But there is a difference between Array.from(obj)
and [...obj]
:
Array.from
works with both pseudo-arrays and iterables.- The
... spread
operator worksonly
with iterable objects.
Therefore, Array.from
is a more general method.
Total
When we see "..."
in code код, it can be either the residual parameters ...rest
or the extension operator ...spread
.
How to distinguish them from each other:
- If
...
is located at the end of the function argument list, then these are "residual parameters". It collects the rest of the unspecified arguments and makes an array of them. - If
...
occurs in a function call or elsewhere, it is an "extension operator". It extracts elements from an array to initialize the function.
It is useful to remember:
Residual parameters are used to create new functions with an undefined number of arguments.
Using the spread operator, you can insert an array into a function that, by default, works with a regular list of arguments. “Together, these constructs make it easy to convert sets of values to and from arrays.
Problems?
Write to Discord chat.
Questions:
If ...
is located at the end of the function argument list, then we are dealing with:
- Residual parameter
- Expansion operator
- Random indicators
To create a function with an undefined number of arguments, use:
- Residual parameters
...rest
- The spread operator
...spread
- External call functions
You can combine two arrays into one using:
- Expansion operator
- The
Array.from
operator - Residual parameter
In order to understand how much you learned this lesson, take the test in the mobile application of our school on this topic or in our telegram bot.
Links
- MDN web doc. Spread syntax article
- Residual Parameters and the Spread Operator article
- The article "The spread and rest operator"
Contributors ✨
Thanks goes to these wonderful people (emoji key):
Dmitriy K. | Dmitriy Vasilev 💵 | Resoner2005 🐛 🎨 🖋 | Navernoss 🖋 🐛 🎨 |