Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing Variable Number of arguments in javascript function argument-list

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, ...)
    {
        ...
    }
like image 876
Navyah Avatar asked Oct 28 '13 07:10

Navyah


People also ask

Can we pass a variable number of arguments to a function JavaScript?

When you call a function in JavaScript, you can pass in any number of arguments, regardless of what the function declaration specifies. There is no function parameter limit. In the above function, if we pass any number of arguments, the result is always the same because it will take the first two parameters only.

Can we pass a variable number of arguments to a function?

To call a function with a variable number of arguments, simply specify any number of arguments in the function call. An example is the printf function from the C run-time library. The function call must include one argument for each type name declared in the parameter list or the list of argument types.

How do you handle various number of arguments in a function?

The * symbol is used to pass a variable number of arguments to a function.


2 Answers

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
like image 89
aga Avatar answered Sep 23 '22 15:09

aga


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

like image 38
Satpal Avatar answered Sep 20 '22 15:09

Satpal