DEV Community

Cover image for ES6: Rest parameters
Naftali Murgor
Naftali Murgor

Posted on

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 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
Enter fullscreen mode Exit fullscreen mode

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

Top comments (0)