
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:
//email variable is created but not assigned any value. var email; if (email === undefined){ console.log("Email is undefined"); } Result: ------------------------- Email is undefined
Example 2:
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:
//email variable is not created at all if(typeof email==='undefined' ){ console.log ("Email is undefined"); } Result: --------------------- Email is undefined
Example 2:
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