I myself typically check to an undefined, and thus default parameter in a cunfction call like this:
function c2(p) {
return !p;
}
So I basically use the ! operator. Drawback is that !0 and !"" is also true.
So when I recently stumbled over this code, I thought I found a better solution:
function c4(p) {
return (typeof p) === 'undefined';
}
My first thought was: why so complicated? I searched the web and the pro of this solution is that the variable under test doe snot evene need to be defined. Great. However, I stll was not convinced, especially as Rhino sometime behaves differently than other engines. So I wrote quickly a small test script like this:
// $EXPERIMENTAL$ $STRICT_MODE$ $WARNING_AS_ERROR$
function c1(p) {
return p === undefined;
}
function c2(p) {
return !p;
}
function c3(p) {
return p == undefined;
}
function c4(p) {
return (typeof p) === 'undefined';
}
console.log("c1");
console.log(c1());
console.log(c1(undefined));
console.log(c1(null));
console.log("\nc2");
console.log(c2());
console.log(c2(undefined));
console.log(c2(null));
console.log("\nc3");
console.log(c3());
console.log(c3(undefined));
console.log(c3(null));
console.log("\nc4");
console.log(c4());
console.log(c4(undefined));
console.log(c4(null));
And I was a bit surprised about the outcome:
c1
true
true
false
c2
true
true
true
c3
true
true
true
c4
true
true
false
So only C2 and C3 bring the desired outcome but not C4?
I have not further investigated yet but wanted to post already.
Note that I will be not reading this board for the a couple of weeks, basically April and May. Will be back in June.
Happy Scripting
Jan