Create varargs functions in JavaScript
This post will discuss how to create varargs functions in JavaScript.
Varargs is a term that refers to variable arguments, which means that a function can accept an arbitrary number of arguments. This can be useful when we want to write a flexible and generic function that can handle different types and amounts of inputs. In JavaScript, there are several ways to create and use varargs functions. Here are some of the common examples:
1. Using arguments object
Every function in JavaScript has access to a special object called arguments, which is an array-like object that contains all the arguments passed to the function. We can use the arguments object to access or iterate over the arguments without specifying them in the parameter list. We can access the arguments by their index, like an array, or loop over them using a for loop or a forEach() function. Here’s an example of how we can achieve this:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
// Call the sum function with different number of arguments function sum() { // Use the arguments object to access the arguments console.log(arguments); let total = 0; // Use a for loop to iterate over the arguments for (let i = 0; i < arguments.length; i++) { total += arguments[i]; } return total; } console.log(sum(1, 2, 3)); // [Arguments] { '0': 1, '1': 2, '2': 3 } // 6 console.log(sum(10, 20)); // [Arguments] { '0': 10, '1': 20 } // 30 console.log(sum()); // [Arguments] {} // 0 |
2. Using rest parameter syntax
The rest parameter is a modern way to create a varargs function using ES6 features. The rest parameter syntax allows us to represent an indefinite number of arguments as an array, which we can pass to other functions or manipulate as we wish. We can use the … operator before the last parameter in the function definition to indicate that it is a rest parameter, and then use it as a normal array inside the function. Here’s an example of how we can achieve this:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
// Define a function that takes any number of arguments function sum(msg, ...args) { // Use the args array to access the arguments console.log(args); // Use a for…of loop to iterate over the arguments let total = 0; for (const arg of args) { total += arg; } // Print the custom message with total console.log(msg + total); } // Call the function with different number of arguments sum("Total is: ", 1, 2, 3); // [1, 2, 3] // Total is : 6 sum("Total is: ", 10, 20); // [10, 20] // Total is : 30 sum("Total is: "); // [] // Total is : 0 |
That’s all about creating varargs functions in JavaScript.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)