javascript tutorial - [5 Solutions] ‘Undefined or Null’ - javascript - java script - javascript array
Problem:
How to determine if variable is undefined or null?
But if WE do this, the JavaScript interpreter halts execution.
Solution 1:
We can use the qualities of the abstract equality operator to do this:
Solution 2:
The standard way to catch null
and undefined
simultaneously is this:
--which is 100% equivalent to the more explicit but less concise:
When writing professional JS, it's taken for granted that [type equality and the behavior of ==
vs ===
][1] is understood. Therefore we use ==
and only compare to null
.
Solution 3:
Solution 4:
Combining the above answers, it seems the most complete answer would be:
This should work for any variable that is either undeclared or declared and explicitly set to null or undefined. The boolean expression should evaluate to false for any declared variable that has an actual non-null value.
Solution 5:
will evaluate to true if value is not:
- null
- undefined
- NaN
- empty string ("")
- 0
- false
Update:Checking undefined
brings more confidence