How to use rest parameters in JavaScript
Rest parameters allow functions to accept an indefinite number of arguments as an array, providing flexible and elegant solutions for variadic functions.
With over 25 years of experience in software development and as the creator of CoreUI, I’ve used rest parameters extensively for building flexible utility functions and component APIs.
From my expertise, the most effective approach is using the three-dot syntax ... followed by a parameter name to collect remaining arguments.
This ES6 feature replaces the need for the arguments object with cleaner, more predictable code.
Use three dots ... followed by a parameter name to collect remaining function arguments into an array.
function sum(...numbers) {
return numbers.reduce((total, num) => total + num, 0)
}
console.log(sum(1, 2, 3, 4)) // 10
Here ...numbers collects all arguments passed to the function into an array called numbers. The rest parameter must be the last parameter in the function signature. Unlike the arguments object, rest parameters create a real array with all array methods available. This allows using array methods like reduce, map, and filter directly on the collected arguments, making the code more functional and easier to work with.
Best Practice Note:
This is the same approach we use in CoreUI components for creating flexible utility functions that accept varying numbers of CSS classes or configuration options. Rest parameters provide better performance and cleaner code than using the legacy arguments object.



