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
SyntaxError: Unexpected token (1:8)
1 : return ()
            ^

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."

Payment#

Now you are on a stripped-down version of the site, after subscribing to Patreon, you will get full access to the training course, as well as access to our server's private channels in Discord.

Download our mobile application or get tested in our JavaScript telegram bot, and also subscribe to our news.

Become a Patron!

Sumerian school

Links#

  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

πŸ–‹ πŸ› 🎨

Become a Patron!