November 20th, 2006

JavaScript: list of implicit true/false values

I got tired of sometimes wondering whether I could use a particular JavaScript value effectively in a conditional statement…
For instance, if I’m in the middle of a block of JS code, and am not 100% sure what the value of a variable will be, is it safe to say:

if (foo)

or do I need to explicitly look at the value of foo, like:

if ((typeof foo != 'undefined') &&
(foo != null) &&
(foo != ''))

So, I took a little time one day, recently, and checked how various values are evaluated in JavaScript. I believe I gathered this info using IE6. Hopefully that fact is not important. Might be worth checking in Firefox one of these days, just to be sure.

false false
0 false
0.0 false
null false
false
undefined false
NaN false
true true
Infinity true
‘ ‘ true
1 true
-1 true
2 true
-2 true
0.1 true
‘0′ true
‘1′ true
‘-1′ true
‘null’ true
‘true’ true
‘false’ true
‘TRUE’ true
‘FALSE’ true

One Response to “JavaScript: list of implicit true/false values”

  1. George Adams Says:

    A handy list - thanks!

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <code> <em> <i> <strike> <strong>