Check Undefined in Javascript: 2 Ways to Do It

Jun 6, 2020

2 mins read

Published in
check if undefined JavaScript

How to check for undefined in JavaScript?

Simple Answer would be to use If condition. there are two type of situation.

1. In case of the variable is defined and not initialised or not assigned.

Example 1:

1
2
3
4
5
var email;

if (email === undefined){
      console.log("Email is undefined");
}
Result:
-------------------------
Email is undefined

Example 2:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
var hadCoffee=false;
      
var isAwake;

if ( hadCoffee ){
     isAwake=true;
}	
//used ! to check the object is initilised or not
if ( !isAwake ) {
     console.log("I hope not...");
}
if ( isAwake==undefined) {
    console.log("I hope not...");
}
if ( isAwake==null) {
     console.log("I hope not...");
}
Result:
---------------------------
I hope not...
I hope not...
I hope not...

In above case we have checked, if variable is defined but not initialised, there are three ways to verify that.

  1. using ” ! “
  2. using ” undefined “
  3. using ” null”

2. In case of variable is not undefined.

Example 1:

1
2
3
4
5
//email variable is not created at all

if(typeof email==='undefined' ){
     console.log ("Email is undefined");
 }
Result:
---------------------
Email is undefined

Example 2:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
const actor = {
  			name: 'Tom Cruise',
  			photo:"Tom-Cruise.jpg"
	  }
if ( actor.name )
      console.log("name:->"+actor.name);
}

if ( typeof actor.age === 'undefined' ){
      console.log("Actor's age is undefined");
}
Result:
---------------------
name:->Tom Cruise
Actor's age is undefined

“typeof” operator of JavaScript can be used to check the object is created or defined. It returns a string in case of the object is available.

Check out Validate JSON String using JavaScript

Also check out Javscript Beautifier tool

Sharing is caring!