javascript - How can I determine if a variable is 'undefined' or 'null'?

ID : 311

viewed : 135

Tags : javascriptjqueryvariablesnullundefinedjavascript

Top 5 Answer for javascript - How can I determine if a variable is 'undefined' or 'null'?

vote vote


You can use the qualities of the abstract equality operator to do this:

if (variable == null){     // your code here. } 

Because null == undefined is true, the above code will catch both null and undefined.

vote vote


The standard way to catch null and undefined simultaneously is this:

if (variable == null) {      // do something  } 

--which is 100% equivalent to the more explicit but less concise:

if (variable === undefined || variable === null) {      // do something  } 

When writing professional JS, it's taken for granted that type equality and the behavior of == vs === is understood. Therefore we use == and only compare to null.

Edit again

The comments suggesting the use of typeof are simply wrong. Yes, my solution above will cause a ReferenceError if the variable doesn't exist. This is a good thing. This ReferenceError is desirable: it will help you find your mistakes and fix them before you ship your code, just like compiler errors would in other languages. Use try/catch if you are working with the input you don't have control over.

You should not have any references to undeclared variables in your code.

vote vote


Combining the above answers, it seems the most complete answer would be:

if( typeof variable === 'undefined' || variable === null ){     // Do stuff } 

This should work for any variable that is either undeclared or declared and explicitly set to null or undefined. The boolean expression should evaluate to false for any declared variable that has an actual non-null value.

vote vote


if (variable == null) {     // Do stuff, will only match null or undefined, this won't match false } 
vote vote


if (typeof EmpName != 'undefined' && EmpName) { 

will evaluate to true if value is not:

  • null

  • undefined

  • NaN

  • empty string ("")

  • 0

  • false

Top 3 video Explaining javascript - How can I determine if a variable is 'undefined' or 'null'?