ES6: Rest parameters

Introduction

In this article, we shall learn about rest parameters.

Rest Parameters

Rest parameters allow several arguments to be supplied to a function. console.log(…args) follows this pattern. We can supply as many arguments…


This content originally appeared on DEV Community and was authored by Naftali Murgor

Introduction

In this article, we shall learn about rest parameters.

Rest Parameters

Rest parameters allow several arguments to be supplied to a function. console.log(...args) follows this pattern. We can supply as many arguments to console.log() because console.log() takes rest parameters.

Example in code snippet showing the rest parameters:

// syntax for rest parameters:
const addSeveralNumbers = (...args) => {
  let result = 0
  args.forEach((num, index) => {
    result += num
  })

  return result
}
const addToTen = addSeveralNumbers(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
console.log(addTo) // prints 55

Summary

  1. Rest parameters allow us to supply a non-fixed number of arguments to a function.
  2. Syntax for rest parameters:function multiply(...args) { // function body}
  3. Calling a function that takes rest parameters is done as one would do with a normal function like multiply(1,2,3,4)
  4. The arguments supplied are accessed as an array of values inside of the function body like in the example

I've rarely used function rest parameters but it's good to learn and know they exist


This content originally appeared on DEV Community and was authored by Naftali Murgor


Print Share Comment Cite Upload Translate Updates
APA

Naftali Murgor | Sciencx (2022-02-08T16:24:27+00:00) ES6: Rest parameters. Retrieved from https://www.scien.cx/2022/02/08/es6-rest-parameters/

MLA
" » ES6: Rest parameters." Naftali Murgor | Sciencx - Tuesday February 8, 2022, https://www.scien.cx/2022/02/08/es6-rest-parameters/
HARVARD
Naftali Murgor | Sciencx Tuesday February 8, 2022 » ES6: Rest parameters., viewed ,<https://www.scien.cx/2022/02/08/es6-rest-parameters/>
VANCOUVER
Naftali Murgor | Sciencx - » ES6: Rest parameters. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2022/02/08/es6-rest-parameters/
CHICAGO
" » ES6: Rest parameters." Naftali Murgor | Sciencx - Accessed . https://www.scien.cx/2022/02/08/es6-rest-parameters/
IEEE
" » ES6: Rest parameters." Naftali Murgor | Sciencx [Online]. Available: https://www.scien.cx/2022/02/08/es6-rest-parameters/. [Accessed: ]
rf:citation
» ES6: Rest parameters | Naftali Murgor | Sciencx | https://www.scien.cx/2022/02/08/es6-rest-parameters/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.