We are frequently using the following code pattern in our JavaScript code
if (typeof(some_variable) != \'undefined\' && some_variable != null)
{
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 },
]);