The rest parameter (...
) allows a function to treat an indefinite number of arguments as an array.
function sum(...args) { let sum = 0; for (let arg of args) sum += arg; return sum; } let x = sum(4, 9, 16, 25, 29, 100, 66, 77); |
JavaScript functions have a built-in arguments
object, which holds an array-like collection of the arguments passed to the function, enabling tasks like finding the highest value in a list of numbers.
x = findMax(1, 123, 500, 115, 44, 88); function findMax() { let max = –Infinity; for (let i = 0; i < arguments.length; i++) { if (arguments[i] > max) { max = arguments[i]; } } return max; } |
Or create a function to sum all the provided input values.
x = sumAll(1, 123, 500, 115, 44, 88); function sumAll() { let sum = 0; for (let i = 0; i < arguments.length; i++) { sum += arguments[i]; } return sum; } |
If a function is called with more arguments than declared, the extra arguments can be accessed through the arguments object. |