Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How to use variable number of arguments to function in JavaScript?
In JavaScript, functions can accept a variable number of arguments using the arguments object or modern rest parameters (...args). The arguments object contains all arguments passed to a function, regardless of how many parameters are defined.
Using the arguments Object
The arguments object is an array-like object that contains all arguments passed to a function:
<html>
<body>
<script>
function functionArgument(val1, val2, val3) {
var res = "";
res += "Expected Arguments: " + functionArgument.length;
res += "<br />";
res += "Current Arguments: " + arguments.length;
res += "<br />";
res += "Each argument = ";
for (var p = 0; p < arguments.length; p++) {
res += "<br />";
res += arguments[p];
res += " ";
}
document.write(res);
}
functionArgument(20, 50, 80, "Demo Text!", "Hello World", new Date());
</script>
</body>
</html>
Expected Arguments: 3 Current Arguments: 6 Each argument = 20 50 80 Demo Text! Hello World Mon Jan 15 2024 10:30:45 GMT-0800 (PST)
Using Rest Parameters (Modern Approach)
ES6 introduced rest parameters (...args) which provide a cleaner way to handle variable arguments:
function sum(...numbers) {
console.log("Number of arguments:", numbers.length);
let total = 0;
for (let num of numbers) {
total += num;
}
return total;
}
console.log(sum(1, 2, 3)); // 3 arguments
console.log(sum(10, 20, 30, 40)); // 4 arguments
Number of arguments: 3 6 Number of arguments: 4 100
Comparison
| Method | Syntax | Array Methods | Modern Support |
|---|---|---|---|
arguments |
arguments[0] |
No (array-like) | All browsers |
| Rest Parameters | ...args |
Yes (true array) | ES6+ |
Practical Example
Here's a function that finds the maximum value from any number of arguments:
function findMax(...values) {
if (values.length === 0) return undefined;
let max = values[0];
for (let i = 1; i < values.length; i++) {
if (values[i] > max) {
max = values[i];
}
}
return max;
}
console.log(findMax(5, 12, 3, 8)); // 4 arguments
console.log(findMax(100, 25, 75, 50, 90)); // 5 arguments
console.log(findMax()); // No arguments
12 100 undefined
Conclusion
Use rest parameters (...args) for modern JavaScript development as they provide true arrays with all array methods. The arguments object is still useful for legacy browser support.
Advertisements
