Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check for both null and undefined in js?

Tags:

javascript

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

if(_var == null || _var == undefined) {

}
like image 749
Blankman Avatar asked May 18 '10 18:05

Blankman


1 Answers

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) { }
like image 83
Daniel Vassallo Avatar answered Oct 06 '22 11:10

Daniel Vassallo