-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?

3
  • 1
    See this answer: stackoverflow.com/a/665056/502381 Commented Jan 26, 2013 at 11:34
  • 1
    @Juhana: This explains the equality comparison algorithm, not how if statements are evaluated. Commented Jan 26, 2013 at 11:42
  • I'm pretty sure this is what the OP is asking, he's just not using the correct terms. Could be wrong though. Commented Jan 26, 2013 at 11:43

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

+1 BTW, there's now a canonical HTML version of the spec: 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: :D The green guy can be really disturbing ;)
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
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.