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.


Speed up your responsive apps and websites with fully-featured, ready-to-use open-source admin panel templates—free to use and built for efficiency.


About the Author

Subscribe to our newsletter
Get early information about new products, product updates and blog posts.
Understanding the Difference Between NPX and NPM
Understanding the Difference Between NPX and NPM

How to Convert a Map to an Array in JavaScript
How to Convert a Map to an Array in JavaScript

How to Center a Button in CSS
How to Center a Button in CSS

How to round a number to two decimal places in JavaScript
How to round a number to two decimal places in JavaScript

Answers by CoreUI Core Team