-1

Possible Duplicate:
Is there a standard function to check for null, undefined, or blank variables in JavaScript?

How is a condition inside the if statement evaluated to true or false in JavaScript?

Community
  • 1
  • 1
dopeddude
  • 4,943
  • 3
  • 33
  • 41

2 Answers2

3

undefined, null, "", 0, NaN, and false are all "falsey" values. Everything else is a "truthy" value.

If you test a "falsey" value, the condition is false. E.g.:

var a = 0;

if (a) {
    // Doesn't happen
}
else {
    // Does happen
}

If you test a "truthy" value, the condition is true:

var a = 1;

if (a) {
    // Does happen
}
else {
    // Doesn't happen
}
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
3

Whatever the result of the condition expression is, it is converted to a Boolean by ToBoolean:

  1. Let exprRef be the result of evaluating Expression.
  2. If ToBoolean(GetValue(exprRef)) is true, then
    Return the result of evaluating the first Statement.
  3. Else,
    Return the result of evaluating the second Statement.

For each data type or value, the conversion rules to a Boolean are clearly defined. So, for example, undefined and null are both converted to false.

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
  • +1 BTW, there's now a canonical HTML version of the spec: http://www.ecma-international.org/ecma-262/5.1/ Not as pretty as es5.github.com, but doesn't have the big weird green guy, either. :-) – T.J. Crowder Jan 26 '13 at 11:53
  • @T.J.Crowder: :D The green guy can be really disturbing ;) – Felix Kling Jan 26 '13 at 11:54