javascript tutorial - [5 Solutions] ‘Undefined or Null’ - javascript - java script - javascript array



Problem:

How to determine if variable is undefined or null?

var EmpName = $("div#esd-names div#name").attr('class');
if(EmpName == 'undefined'){
  //DO SOMETHING
};
<div id="esd-names">
  <div id="name"></div>
</div>
click below button to copy the code. By JavaScript tutorial team

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

Solution 1:

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

if (variable == null){
    // our code here.
}
Because null == undefined is true, the above code will catch both null and undefined.
click below button to copy the code. By JavaScript tutorial team

Solution 2:

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

if (variable == null) {
     // do something 
}
click below button to copy the code. By JavaScript tutorial team

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

if (variable === undefined || variable === null) {
     // do something 
}
click below button to copy the code. By JavaScript tutorial team

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

Solution 3:

if (variable == null) {
    // Do stuff, will only match null or undefined, this won't match false
}
click below button to copy the code. By JavaScript tutorial team

Solution 4:

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

if( typeof variable === 'undefined' || variable === null ){
    // Do stuff
}
click below button to copy the code. By JavaScript tutorial team

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.

Solution 5:

	if (typeof EmpName != 'undefined' && EmpName) {
click below button to copy the code. By JavaScript tutorial team

will evaluate to true if value is not:

  • null
  • undefined
  • NaN
  • empty string ("")
  • 0
  • false

Update:Checking undefined brings more confidence


Related Searches to javascript tutorial - ‘Undefined or Null’