• Skip to main content
  • Skip to primary sidebar

CodeBlogMoney

Make Money using Coding and Blogging

You are here: Home / JavaScript / Check Undefined in Javascript: 2 ways to do it

Check Undefined in Javascript: 2 ways to do it

June 7, 2020 by Jimmy

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:

//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.

  1. using ” ! “
  2. using ” undefined “
  3. 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

Filed Under: JavaScript Tagged With: Javascript

Primary Sidebar

Categories

  • Blogging
  • HTML
  • Java
  • JavaScript
  • jQuery
  • JSON
  • MySql
  • Performance
  • PHP
  • Problem Solving
  • Python
  • Testing
  • XML

Copyright © 2021 · Metro Pro on Genesis Framework · WordPress · Log in