Javascript if expression evaluation

I was wondering when the Javascript if expression really evaluates to false and when true . When the operator of if false , and - this is true for all interpreters of JS?

I assume the condition is false on

  • false
  • undefined
  • null
  • 0

otherwise true . Is this correct for all implementations (verified in the Safari / WebKit console), or is it better for me with explicit verification, for example (typeof a === "undefined") ?

+6
source share
2 answers

The following values ​​will be calculated as false:

  • False
  • undefined
  • Null
  • 0
  • NaN
  • empty line ("")

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

+10
source

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

Your guess seems correct. An empty string and NaN are also evaluated as false (or, like some of them, falsy ). The fact that 0 evaluates to false can be tricky, but it is also convenient in expressions such as while (i--) (if i is 0, it evaluates to false and the while loop stops).

+1
source

Source: https://habr.com/ru/post/911077/


All Articles