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

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

+27
javascript parameters
Dec 04 '09 at 12:31
source share
5 answers

Set the value to undefined. You do not get an exception. This can be a convenient way to make your function more versatile in certain situations. Undefined evaluates to false, so you can check if the value has been passed.

+26
Dec 04 '09 at 12:38
source share
— -

javascript will set any missing parameters to 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 the arguments provided, even if you supply more than is required by the function definition.

+12
Dec 04 '09 at 12:35
source share

There is an opposite answer to everything that you can call a function that has no parameters in the signature with the parameters.

You can then access them using the built-in arguments global. This is an array from which you can get data.

eg.

 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)) 
+6
Dec 04 '09 at 12:43
source share

In addition to the comments above, the arguments array has zero length. It can be checked, not the parameters named in the function signature.

+3
Dec 04 '09 at 12:43
source share

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

-7
Dec 04 '09 at 12:33
source share



All Articles