Is it possible to check for both null and undefined in javascript?
if(_var == null || _var == undefined) {
}
In JavaScript (pre ECMAScript 5), undefined is not a constant, but a global variable, and therefore it is possible to change its value. Therefore it would be more reliable to use the typeof operator to check for undefined:
if (typeof _var === 'undefined') { }
In addition your expression would return a ReferenceError if the variable _var is not declared. However you would still be able to test it with the typeof operator as shown above.
Therefore, you may prefer to use the following:
if (typeof _var === 'undefined' || _var === null) { }
undefined is a property of the global object which is non-writable, non-configurable (non-deletable) and non-enumerable :)yes
However using the == operator it is not necesary. using foo == null will also be true of foo is undefined. Note however that undefined and null or not(!) the same. It is because that == does type coersion that foo == null is also true for foo is undefined.
if (_var == null) { ... }if (!_var) {
// Code here.
}
This should work since both undefined and null are type coerced to false.
Of course there is the small problem if _var is actually false but it works since in most cases you would want to know if _var is not true and not an object.
false, null and undefined: An empty string "", 0, and NaN.
_varisundefined, the_var == undefinedexpression will never be reached, because_var == nulldoes type coercion, as Pim noted below andundefined == nullreturnstrue. The_var == nullwill also be testing forundefined, however I believe relying on type coercion is not generally recommended.