views:

160

answers:

5

What happens when I call a Javascript function which takes parameters, without supplying those parameters?

A: 

You get an exception as soon as you try to use one of the parameters.

Aaron Digulla
+1  A: 

javascript will set any missing parameters to the value undefined.

function fn(a) {
    console.log(a);
}

fn(1); // outputs 1 on the console
fn(); // outputs undefined on the console

This works for any number of parameters.

function example(a,b,c) {
    console.log(a);
    console.log(b);
    console.log(c);
}

example(1,2,3); //outputs 1 then 2 then 3 to the console
example(1,2); //outputs 1 then 2 then undefined to the console
example(1); //outputs 1 then undefined then undefined to the console
example(); //outputs undefined then undefined then undefined to the console

also note that the arguments array will contain all arguments supplied, even if you supply more than are required by the function definition.

barkmadley
+1  A: 

Set to undefined. You don't get an exception. It can be a convenient method to make your function more versatile in certain situations. Undefined evaluates to false, so you can check whether or not a value was passed in.

KP
And what if your function can take five parameters, but you only supply two? Same thing?
Krummelz
the first two are accepted, the following three are set to undefined
David Hedlund
furthermore, you can acctually supply *more* parameters than the function accepts. you can then access all parameters by the `arguments` collection. `function test(param1) { alert(param1); if(arguments.length == 2) alert(arguments[1]); } test(); test(1); test(1,2);`
David Hedlund
A: 

There is the inverse to everyones answer in that you can call a function that doesnt appear to have parameters in the signature with parameters.

You can then access them using the built in arguments global. This is an array that you can get the details out of it.

e.g.

function calcAverage() 
{ 
   var sum = 0 
   for(var i=0; i<arguments.length; i++) 
      sum = sum + arguments[i] 
   var average = sum/arguments.length 
   return average 
} 
document.write("Average = " + calcAverage(400, 600, 83))
AutomatedTester
+1  A: 

In addition to the comments above, the arguments array has zero length. One can examine it rather than the parameters named in the function signature.

Upper Stage