You can use and test uninitialized variables, at least for your "certainty." Like this:
var iAmNotDefined; alert(!iAmNotDefined); //true //or alert(!!iAmNotDefined); //false
In addition, there are many possibilities: if you are not interested in the exact types, use the '==' operator (or! [Variable] / !! [variable]) to compare (this is what Douglas Crockford calls โtrueโ or โfalseโ ', I think). In this case, assigning true or 1 or '1' for a unified variable always returns true when prompted. Otherwise [if you need safe type comparisons] use '===' for comparison.
var thisMayBeTrue; thisMayBeTrue = 1; alert(thisMayBeTrue == true); //=> true alert(!!thisMayBeTrue); //=> true alert(thisMayBeTrue === true); //=> false thisMayBeTrue = '1'; alert(thisMayBeTrue == true); //=> true alert(!!thisMayBeTrue); //=> true alert(thisMayBeTrue === true); //=> false // so, in this case, using == or !! '1' is implicitly // converted to 1 and 1 is implicitly converted to true) thisMayBeTrue = true; alert(thisMayBeTrue == true); //=> true alert(!!thisMayBeTrue); //=> true alert(thisMayBeTrue === true); //=> true thisMayBeTrue = 'true'; alert(thisMayBeTrue == true); //=> false alert(!!thisMayBeTrue); //=> true alert(thisMayBeTrue === true); //=> false // so, here no implicit conversion of the string 'true' // it also a demonstration of the fact that the // ! or !! operator tests the 'definedness' of a variable.
PS: you cannot check "certainty" for non-existent variables. So:
alert(!!HelloWorld);
gives an Error link ("HelloWorld undefined")
(is there a better word for โdefinitenessโ?) I apologize for my Dutch language;)
KooiInc Mar 17 '09 at 13:06 2009-03-17 13:06
source share