This content originally appeared on Go Make Things and was authored by Go Make Things
On Friday, we looked at the arguments
object in JavaScript functions. Today, we’re going to look at rest parameters.
Rest parameters work a lot like the arguments
object, but with two notable advantages.
- You can give them to any name you’d like.
- You can start at any parameter you want.
You define rest parameters by creating a parameter prefixed with ...
. Any arguments provided at or beyond the rest parameter on a function get combined into an array that’s assigned to the rest parameter’s name.
In the example below, ...moreArgs
is a rest parameter.
function logStuff (arg1, arg2, ...moreArgs) {
// Logs arg1
console.log(arg1);
// Logs arg2
console.log(arg2);
// Logs an array of any other arguments you pass in after arg2
console.log(moreArgs);
}
// In this example...
// arg1 = 'chicken'
// arg2 = 'tuna'
// moreArgs = ['chips', 'cookie', 'soda', 'delicious']
logStuff('chicken', 'tuna', 'chips', 'cookie', 'soda', 'delicious');
Unlike the arguments
object, rest parameters are traditional arrays that can be used with all of the array methods. Here’s a demo.
Here’s a function you can use to add()
two or more numbers together, written with a rest parameter.
function add (...nums) {
// Set a starting total
let total = 0;
// Add each number to the total
nums.forEach(function (num) {
total += num;
});
// Return to the total
return total;
}
One other notable benefit of rest parameters over the arguments
object: they work in ES6 arrow functions (the arguments
object does not).
This content originally appeared on Go Make Things and was authored by Go Make Things

Go Make Things | Sciencx (2021-03-22T14:30:00+00:00) Rest parameters in JavaScript functions. Retrieved from https://www.scien.cx/2021/03/22/rest-parameters-in-javascript-functions/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.