6

I was wondering when the Javascript if expression actually evaluates to false and when to true. When is the if statement false, and is that true for all JS interpreters?

I guess the condition is false on

  • false
  • undefined
  • null
  • 0

otherwise true. Is that correct for all implementations (tested in Safari/WebKit console), or am I better off with explicit checking like (typeof a === "undefined")?

2 Answers 2

9

The following values will evaluate to false:

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

https://developer.mozilla.org/en/JavaScript/Guide/Statements#if...else_Statement

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

2 Comments

Thank you! Did overlook that!
Just to know -- What is the order of evaluation in multiple JS if() conditions? Left to right or right to left?
0

If you want to check for variable existence, and a is not declared anywhere in your script, typeof a === 'undefined' is the way, or you can use if (!window.a). Otherwise a ReferenceError is thrown.

Your guessing seems to be correct. An empty string and NaN also evaluate to false (or, as some like it falsy). The fact that 0 evaluates to false may be tricky, but it's handy too, in statements like while (i--) (if i has the value of 0 it evaluates to false and the while loop stops).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.