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, ...)
    {
        ...
    }
5
  • yes you can :-) heres a good tutorial w3schools.com/js/js_functions.asp 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 Commented Oct 28, 2013 at 7:19
  • yes...you can pass any number of parameters...javascript.info/tutorial/arguments Commented Oct 28, 2013 at 7:19
  • Javascript supports passing of multiple parameters through function. Commented Oct 28, 2013 at 7:20
  • possible duplicate of JavaScript variable number of arguments to function Commented Jan 21, 2015 at 6:00

3 Answers 3

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
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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])
  }
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.