Skip to main content

Rest and Spread

@serverSerrverlesskiy

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)

Parametrs

You can call a function⚙️ with any number of arguments, regardless of how it was defined.

For example :

Live Editor
Result
Loading...

Extra arguments will not cause an error, but of course only the first three will be counted.

ES6 concept

Idea

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:

Live Editor
Result
Loading...

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.

paste

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] :

Live Editor
Result
Loading...

Possible mistakes

error

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!
}
Remember

... rest must always be last.

Spread operator ... spread

operators

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:

Live Editor
Result
Loading...

Not so simple

Index_finger

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.

Live Editor
Result
Loading...

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

Transform

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 :

Live Editor
Result
Loading...

In the same way, we can pass multiple iterables :

Live Editor
Result
Loading...

Cool! A very flexible approach to programming. You can also combine the spread operator with normal values.

Merging Arrays

Merger

The spread operator ... spread can also be used to merge arrays :

Live Editor
Result
Loading...

Converting to string

Transform

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]

spread

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

spread

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 works only with iterable objects.

Therefore, Array.from is a more general method.

Total

Elipsis

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.

    EnglishMoji!

Problems?

Problem

Write to Discord chat.

Questions:

Question

If ... is located at the end of the function argument list, then we are dealing with:

  1. Residual parameter
  2. Expansion operator
  3. Random indicators

To create a function with an undefined number of arguments, use:

  1. Residual parameters ...rest
  2. The spread operator ...spread
  3. External call functions

You can combine two arrays into one using:

  1. Expansion operator
  2. The Array.from operator
  3. 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.

EnglishMoji!

  1. MDN web doc. Spread syntax article
  2. Residual Parameters and the Spread Operator article
  3. The article "The spread and rest operator"

Contributors ✨

Thanks goes to these wonderful people (emoji key):


Dmitriy K.


Dmitriy Vasilev

💵

Resoner2005

🐛 🎨 🖋

Navernoss

🖋 🐛 🎨