Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript not passing all the parameters

Tags:

javascript

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'?

like image 514
Paul L Avatar asked Aug 02 '10 03:08

Paul L


People also ask

How many parameters can be passed to a function in JavaScript?

param The name of an argument to be passed to the function. A function can have up to 255 arguments.

What happens if you pass an extra parameter to a method in JavaScript?

Unless otherwise specified in the description of a particular function, if a function or constructor described in this clause is given more arguments than the function is specified to allow, the extra arguments are evaluated by the call and then ignored by the function.

Do I always have to add parameters to every function in JS?

Nothing will happen- meaning you won't get an error or a warning as passing the parameters in javascript is optional. All the parameters that weren't "supplied" will have the undefined value. You can even pass more arguments, like: foo(1,2,3,4,5,7); // Valid!

Can a JavaScript function have no parameters?

The functions have different structures such as parameters or no parameters and some function return values and some do not in JavaScript. The simplest of function is the one without an parameters and without return. The function compute its statements and then directly output the results.


1 Answers

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.

like image 190
Nick Craver Avatar answered Nov 05 '22 07:11

Nick Craver