Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

How do I determine if variable is undefined or null?

My code is as follows:

var EmpName = $("div#esd-names div#name").attr('class'); if(EmpName == 'undefined'){   // DO SOMETHING }; 
<div id="esd-names">   <div id="name"></div> </div> 

But if I do this, the JavaScript interpreter halts execution.

like image 427
sadmicrowave Avatar asked Apr 15 '10 18:04

sadmicrowave


People also ask

How do you know if a variable is undefined or null?

Finally, the standard way to check for null and undefined is to compare the variable with null or undefined using the equality operator ( == ). This would work since null == undefined is true in JavaScript. That's all about checking if a variable is null or undefined in JavaScript.

How do you know if its undefined or not?

In a JavaScript program, the correct way to check if an object property is undefined is to use the typeof operator. If the value is not defined, typeof returns the 'undefined' string.

Is it null or undefined?

Difference Between undefined and nullundefined is a variable that refers to something that doesn't exist, and the variable isn't defined to be anything. null is a variable that is defined but is missing a value.


2 Answers

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.

like image 95
Sarfraz Avatar answered Sep 19 '22 17:09

Sarfraz


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.

like image 21
temporary_user_name Avatar answered Sep 19 '22 17:09

temporary_user_name