Can I pass a variable number of arguments into a Javascript function? I have little knowledge in JS. I want to implement something like the following:
function CalculateAB3(data, val1, val2, ...)
{
...
}
Can I pass a variable number of arguments into a Javascript function? I have little knowledge in JS. I want to implement something like the following:
function CalculateAB3(data, val1, val2, ...)
{
...
}
Share
Improve this question
edited Oct 28, 2013 at 7:50
qaphla
4,7333 gold badges21 silver badges31 bronze badges
asked Oct 28, 2013 at 7:16
NavyahNavyah
1,68011 gold badges33 silver badges59 bronze badges
5
- yes you can :-) heres a good tutorial w3schools.com/js/js_functions.asp – StaleMartyr Commented Oct 28, 2013 at 7:18
- 3 You can pass multiple arguments, but the better way is that you can pass an object or an array instead – AmGates Commented Oct 28, 2013 at 7:19
- yes...you can pass any number of parameters...javascript.info/tutorial/arguments – shemy Commented Oct 28, 2013 at 7:19
- Javascript supports passing of multiple parameters through function. – Jenz Commented Oct 28, 2013 at 7:20
- possible duplicate of JavaScript variable number of arguments to function – Alexis King Commented Jan 21, 2015 at 6:00
3 Answers
Reset to default 15You can pass multiple parameters in your function and access them via arguments variable. Here is an example of function which returns the sum of all parameters you passed in it
var sum = function () {
var res = 0;
for (var i = 0; i < arguments.length; i++) {
res += parseInt(arguments[i]);
}
return res;
}
You can call it as follows:
sum(1, 2, 3); // returns 6
Simple answer to your question, surely you can
But personally I would like to pass a object rather than n
numbers of parameters
Example:
function CalculateAB3(obj)
{
var var1= obj.var1 || 0; //if obj.var1 is null, 0 will be set to var1
//rest of parameters
}
Here ||
is logical operator for more info visit http://codepb.com/null-coalescing-operator-in-javascript/
A Is there a "null coalescing" operator in JavaScript? is a good read
Yes, you can make it. Use variable arguments
like there:
function test() {
for(var i=0; i<arguments.length; i++) {
console.log(arguments[i])
}
}