views:

52

answers:

1

Hello!

What kind of variables will NOT pass through this:

if(myVar){//code}

Boolean false? NULL? Boolean false and NULL? Anything else?

Thank you.

+9  A: 

All the following falsy values as:

  • null
  • undefined
  • NaN
  • 0
  • "" (an empty string)
  • false

Anything else converted to Boolean will yield true.

More info:

CMS
if `myVar` is undefined you'll get a script error.
lincolnk
@lincolnk: if `myVar` is **undeclared** you will get a `ReferenceError`. A variable can be declared and hold `undefined` as its value, for example, when you declare a variable without initialize it with a value: `var myVar;` it will be **declared**, but uninitialized, it will hold `undefined` as its value, e.g. `alert(myVar);` will alert `"undefined"`. At some point you can also assign the `undefined` value to it, e.g. `myVar = undefined;`. Remember, **undeclared** != `undefined`
CMS
ok, that all makes sense. `typeof <undeclared name>` produces 'undefined' in IE, which is throwing me off.
lincolnk
@lincolnk: Yeah, if the operand expression of the [`typeof` operator](http://ecma262-5.com/ELS5_HTML.htm#Section_11.4.3) is an *unresolvable reference* (it doesn't exist in the scope chain), will explicitly return the string `"undefined"`.
CMS
- Note that all the above are *primitive values*, any object, even the Boolean object wrappers will always produce `true`, e.g.: `if (new Boolean(false)) { alert('Javascript FTW!'); }` -
CMS
Wow, lots of errors can happen if you don't know this. Thanks a lot, CMS, much appreciated.
Francisc
Hm, what would "0" (string 0) yield? And are the values specified in your answer cross-browser consistent?
Francisc
@Francisc: A string, converted to Boolean will produce `false` **only** when its length is `0` (an empty string), that's not the case of `"0"` (it's length is `1`). You can test this easily simply by `alert(!!"0");` or `alert(Boolean("0"));` which will give you `true`. And yes, the values I describe are based on the ECMAScript language specification, they are implemented cross-browser consistently.
CMS
@CMS, +1, good stuff as usual.
Tim Down
Excellent, thank you. After reading the link you provided I saw it said "false if the argument is the empty String".
Francisc
Thanks @Tim! :-)
CMS