In ColdFusion, I am very confident about what values will be implicitly converted to true / false boolean values. In Javascript, however, my confidence is much lower. I know that objects will be false if they are "null", but what about things like numeric values? I end up writing code like this:
Launch code in new window » Download code as text file »
... because I'm never sure how "strValue.length" will be used without explicit comparisons. This not only demonstrates a lack of understanding in the language, it also means excess code and a lower signal-to-noise ratio. Shame on me!
Well, not no more! Now, I am finally testing all of these values to check the implicit boolean value conversions that Javascript will do for me:
Launch code in new window » Download code as text file »
Running the above code, we get the following output:
true: TRUE
false: FALSE
null: FALSE
Zero: FALSE
Positive Num: TRUE
Negative Num: TRUE
String Length: TRUE
Zero String Length: FALSE
Array Length: TRUE
Zero Array Length: FALSE
Object: TRUE
Array: TRUE
Zero AND true: FALSE
Zero AND One: FALSE
1 AND -1: TRUE
I think the biggest confidence builder here is that fact that the number zero is considered false and that any NON-zero number (positive or negative) is considered true. This will make my code much more readable (to me). Sweet! That's what happens when you go ahead and test stuff - you get rid of the mystery.
Download Code Snippet ZIP File
Comments (2) | Post Comment | Ask Ben | Permalink | Other Searches | Print Page
Ask Ben: Environment-Based Application.cfc Settings
Passing Referer AS ColdFusion CFHttp CGI Value vs HEADER Value?
Save even more chars:
Empty string ("") is also false.
Btw, you may use "double negation" instead of "if" statement to convert any value to boolean:
var bool = !!someVar;
So
!!0 == false;
!!1 == true;
!!"ABC" == true;
!!"" == false;
Valery
Posted by Valery on Aug 13, 2007 at 6:44 AM
Empty string is false. Very interesting. I am not sure exactly how I feel about that, but lo and behold, I just tested it and you are dead on the money. I like it, thanks for the hot tip.
Posted by Ben Nadel on Aug 13, 2007 at 7:18 AM