If you want to allow 0
and ""
as valid values and you want to cover the case of the variable might not even be delcared, but don't consider null a valid value, then you have to specifically check for undefined
and null
like this:
if (typeof myVar !== 'undefined' && myVar !== null)
...
A lot of values are falsey (they don't satisfy if (myVar)
so you really have to conciously decide which ones you're testing for. All of these are falsey:
undefined
false
0
""
null
NaN
If you want to allow some, but not others, then you have to do a more specific test than if (myVar)
like I've shown above to isolate just the values you care about.
Here's a good writeup on falsey values: http://www.sitepoint.com/javascript-truthy-falsy/.
If you know the variable has been declared and you just want to see if it's been initialized with something other than null, you can use this:
if (myVar != undefined)
...
Using only the !=
instead of !==
allows this to test for both undefined and null via type conversion. Although, I wouldn't recommend this because if you're trying to discern between falsey values, it's probably better to NOT let the JS engine do any type conversions at all so you can control exactly what it does without having to memorize all the type conversion equality rules. I'd stick with this to be more explicit:
if (typeof myVar !== 'undefined' && myVar !== null)
...
If you want to know if it has any non-falsey value, you can of course do this (but that won't allow 0
or ""
as valid values:
if (myVar)
...