We are frequently using the following code pattern in our JavaScript code
if (typeof(some_variable) != \'undefined\' && some_variable != null)
{
Testing nullity (if (value == null)
) or non-nullity (if (value != null)
) is less verbose than testing the definition status of a variable.
Moreover, testing if (value)
(or if( obj.property)
) to ensure the existence of your variable (or object property) fails if it is defined with a boolean false
value. Caveat emptor :)
If you try and reference an undeclared variable, an error will be thrown in all JavaScript implementations.
Properties of objects aren't subject to the same conditions. If an object property hasn't been defined, an error won't be thrown if you try and access it. So in this situation you could shorten:
if (typeof(myObj.some_property) != "undefined" && myObj.some_property != null)
to
if (myObj.some_property != null)
With this in mind, and the fact that global variables are accessible as properties of the global object (window
in the case of a browser), you can use the following for global variables:
if (window.some_variable != null) {
// Do something with some_variable
}
In local scopes, it always useful to make sure variables are declared at the top of your code block, this will save on recurring uses of typeof
.
This is an example of a very rare occasion where it is recommended to use ==
instead of ===
. Expression somevar == null
will return true for undefined
and null
, but false for everything else (an error if variable is undeclared).
Using the !=
will flip the result, as expected.
Modern editors will not warn for using ==
or !=
operator with null
, as this is almost always the desired behavior.
Most common comparisions:
undeffinedVar == null // true
obj.undefinedProp == null // true
null == null // true
0 == null // false
'0' == null // false
'' == null // false
Try it yourself:
let undefinedVar;
console.table([
{ test : undefinedVar, result: undefinedVar == null },
{ test : {}.undefinedProp, result: {}.undefinedProp == null },
{ test : null, result: null == null },
{ test : false, result: false == null },
{ test : 0, result: 0 == null },
{ test : '', result: '' == null },
{ test : '0', result: '0' == null },
]);
Similar to what you have, you could do something like
if (some_variable === undefined || some_variable === null) {
do stuff
}
With Ramda, you can simply do R.isNil(yourValue)
Lodash and other helper libraries have the same function.
Best way to compare undefined or null or 0 with ES5 and ES6 standards
if ((Boolean(some_variable_1) && Boolean(some_variable_2)) === false) {
// do something
}