8

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, ...)
    {
        ...
    }
qaphla
  • 4,707
  • 3
  • 20
  • 31
Navyah
  • 1,660
  • 10
  • 33
  • 58
  • yes you can :-) heres a good tutorial http://www.w3schools.com/js/js_functions.asp – StaleMartyr Oct 28 '13 at 07:18
  • 3
    You can pass multiple arguments, but the better way is that you can pass an object or an array instead – AmGates Oct 28 '13 at 07:19
  • yes...you can pass any number of parameters...http://javascript.info/tutorial/arguments – shemy Oct 28 '13 at 07:19
  • Javascript supports passing of multiple parameters through function. – Jenz Oct 28 '13 at 07:20
  • possible duplicate of [JavaScript variable number of arguments to function](http://stackoverflow.com/questions/2141520/javascript-variable-number-of-arguments-to-function) – Alexis King Jan 21 '15 at 06:00

3 Answers3

15

You 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
aga
  • 27,954
  • 13
  • 86
  • 121
3

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

Community
  • 1
  • 1
Satpal
  • 132,252
  • 13
  • 159
  • 168
0

Yes, you can make it. Use variable arguments like there:

function test() {
  for(var i=0; i<arguments.length; i++) {
    console.log(arguments[i])
  }
}
MD. Khairul Basar
  • 4,976
  • 14
  • 41
  • 59
eterey
  • 390
  • 1
  • 4
  • 16