How to determine if the variable is undefined or null in Javascript?

How to determine if the variable is undefined or null in JavaScript? The easiest way is to check if the variable is null. As null == undefined, checking for null indirectly also checks for undefined. To determine if the variable is null or undefined in AngularJS click here.

In this blog, we will see 4 different ways of to determine if the variable is undefined or null. The demo is available on JSFiddle.

  • Method 1

The basic way is to check for null. As null == undefined, checking for null indirectly also checks for undefined.

var name="yoUVcode";

if (name== null){
     // your code here
}
  • Method 2

Check if the variable is initialized or not.

var name="yoUVcode";

if (!name){
     // your code here
}
  • Method 3

This will work for any variable that is either undeclared or declared and explicitly set to null or undefined. Else condition will be executed for a non null value.

var name="yoUVcode"; 

if (typeof name=== 'undefined' || name === null){
     // your code here
}
  • Method 4

Check if the value is undefined. This is similar to Method 1. As null == undefined, checking for undefined indirectly also checks for null.

var name="yoUVcode";

if (name === undefined){
     // your code here
}

The complete demo is available on JSFiddle. To check if the JavaScript Object / Array is empty or not click here.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.