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.
using ” ! “
using ” undefined “
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.
Sharing is caring!