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
- Rest parameters allow us to supply a non-fixed number of arguments to a function.
- Syntax for rest parameters:
function multiply(...args) { // function body}
- Calling a function that takes rest parameters is done as one would do with a normal function like
multiply(1,2,3,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
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/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.