What happens when I call a Javascript function which takes parameters, without supplying those parameters?
views:
160answers:
5You get an exception as soon as you try to use one of the parameters.
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.
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.
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))
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.