How to check both null and undefined in js?

Is it possible to check both null and undefined in javascript?

if(_var == null || _var == undefined) { } 
+6
javascript
source share
5 answers

In JavaScript (pre ECMAScript 5 ), undefined not a constant, but a global variable, and therefore you can 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 will return a ReferenceError if the _var variable is not declared. However, you can still verify it using the typeof operator, as shown above.

Therefore, you can use the following:

 if (typeof _var === 'undefined' || _var === null) { } 
+7
source share

Yes

However, using the == operator is optional. using foo == null will also be true for foo undefined. Note, however, that undefined and null or not (!) Is the same. This is because it is == type coersion, which foo == null is also true for foo undefined.

+4
source share
 if (!_var) { // Code here. } 

This should work, since both undefined and null are false .

Of course, there is a small problem if _var is actually false , but it works, because in most cases you need to know, not _var not true , not the object.

+1
source share

you can also use the $defined function in mootools (and there should be an equivalent in jQuery)

0
source share
 var valuea: number; var valueb: number = null; function check(x, name) { if (x == null) { console.log(name + ' == null'); } if (x === null) { console.log(name + ' === null'); } if (typeof x === 'undefined') { console.log(name + ' is undefined'); } } check(a, 'a'); check(b, 'b'); 
0
source share

All Articles