tags:

views:

58

answers:

3

Hi, is that possible to call Javascript function without supply all the parameters?

I come across a line of code doesn't make much sense unless I assume that in Javascript supply all the parameters are not required?

The parameter been missed is a boolean value, so could I further assume that undefined boolean value in Javascript equal to 'false'?

+5  A: 

Yes, the other parameters will just be undefined if they're not passed in :)

For example:

function myFunc(param1, param2) {
  alert(param1);
  alert(param2);
}

This is a valid call:

myFunc("string"); //alerts "string" then undefined

Give it a try here. If the check in your question is something like if(!param2), it'll evaluate to true, since undefined ~= false for most purposes. It's worth noting this is not only acceptable, it's very common, almost every library or framework expects only some of the parameters to be passed into most of their functions.

Nick Craver
Thank you, all clear now.And jsFiddle is great!
pstar
+1 i was just adding to your excellent answer...
davidsleeps
+2  A: 

Adding to Nick's response, you could have:

// set the value to false if not passed
if (typeof(param2) === "undefined") param2 = false;
davidsleeps
Good addition, so missed parameter is not 'true' nor 'false'?
pstar
Nick points out that the value is undefined...which is not equal to false...this is just a way of explicitly checking to see if it is undefined and then setting it to a default (As per your suggested value)
davidsleeps
er...you should probably make Nick's the answer really...
davidsleeps
param2 = param2 || false;
Ben Rowe
A: 

You may also use Variadic Functions in javascript. You can actually pass any type/number of parameters to any javascript function and use arguments to retrieve those parameters.

function PrintList()
{
  for (var i = 0; i < arguments.length; i++)
  {
    document.write(arguments[i] + "<br />");
  }
}
// Calls to Function
PrintList('Google');
PrintList('Google', 'Microsoft', 'Yahoo');
PrintList('Google', 'Microsoft', 'Yahoo', 'Adobe');
Ramesh Soni