I want to pass the value of \'undefined\' on a multiple parameter function but without omitting the parameter.
What do I mean with \"without omitting the paramet
You can use apply and an array of parameters to pass "undefined" as one of the parameters. For example, you wanted to pass parm1 as "undefined":
function myFunction (parm1, parm2) {
if(typeof (parm1) === "undefined"){
alert("parm1 is undefined")
}
if(typeof (parm2) === "undefined"){
alert("parm2 is undefined")
}
}
var myParameters = [undefined, "abc"];
myFunction.apply(valueForThis, myParameters );
myFunction(undefined,"abc");
this way should work, what is the problem?
see here
Here is undefined documentation from mozilla, supported by all browsers
Try to use this method if you plan on adding an indefinite amount of parameters:
function myFunc(params) {
// Define default values
var name = 'John';
var age = '40';
// You can loop through them
for (var p in params) {
alert(p + ':' + params[p]);
}
// And read them in like this
if (typeof params.name != 'undefined') {
name = params.name;
}
if (typeof params.age != 'undefined') {
age = params.age;
}
alert(name + ' ' + age);
}
alert('test1');
myFunc({name:'Bob', age:'30'});
alert('test2');
myFunc({name:'Bob'});
You need to handle the function call with undefined variable in the function code itself in one of the following way :-
function myFunction (parm1, parm2) {
if (parm1 !== undefined) {
// execute code if 1st param is undefined
}
if (parm2 !== undefined) {
// execute code if 2 param is undefined
}
// execute other part of code
}
Now you can call the above function in following ways:-
myFunction(undefined,"abc"); // with 1st param value not known
myFunction("cde",undefined); // with 2nd param value not known
myFunction("cde","abc"); // with both param value known
A better approach might be passing Object
with named attributes and then look for those specific attribute values. This way you don't have to be dependent on number of arguments.
Example: Object.dummy
I just had an idea and it seems to work:
var undf;
myFunction(undf, "abc");
I am sure there are better ways, however I post this