Reputation: 966
I'm reading a book that says that while it's possible to test whether a variable is defined and has a value by doing:
if(myVar != null && myVar != undefined) {
...
}
this is considered “poor style”, and that since both null
and undefined
are falsey values, we can more easily check if a variable has a value by using the more concise if
construct
if(myVar) {
...
}
But this confuses me, because while it’s true that null
and undefined
are falsey values, they are not the only falsey values. In other words, it seems to me that the former if
statement says, "run the code as long as the variable isn't null or undefined, whereas the latter if
statement is saying, "run the code as long as the variable isn't falsey." Supposing myVar == 0
, then the former if
statement would run, but the latter if
statement would not. Therefore these two if
statements are not equivalent. Am I wrong?
EDIT: Here's a screen grab if you want to see their exact wording:
Upvotes: 5
Views: 1776
Reputation: 1290
There isn't a short way. You first need to check for undefined before null, because
!myVar
makes the assumption that myVar is previously defined, and will throw
Uncaught ReferenceError: myVar is not defined
in the event that you never defined that variable.
This check is only required if you're pulling data from some external source and are unsure if the variable exists. If you already defined it somewhere in your code and are for instance waiting for user input to set it, you can take the shortcut of
!myVar
simply because you know it's already defined because you did it earlier in the code.
Upvotes: 2
Reputation: 20633
To check if the variable is either null
or undefined
, use the not single equal operator checking for null
.
if (myVar != null) {
}
However, it's always best practice to use triple equals to be more explicit.
if (!(myVar === null || typeof myVar === 'undefined')) {
}
Comparisons
(undefined == null) => true
(null == null) => true
(undefined === null) => false
(null === null) => true
(0 == null) => false
(0 == undefined) => false
(0 === null) => false
(0 === undefined) => false
(false == null) => false
(false == undefined) => false
(false === null) => false
(false === undefined) => false
(null) => false
(undefined) => false
(0) => false
(false) => false
DEMO: http://jsfiddle.net/xk9L3yuz/3/
Upvotes: 5