Table of contents

How To Check Empty, Null, and Undefined Variables in Javascript / jQuery?

In this post, I will share a basic code in Javascript/jQuery that checks the empty, null, and undefined variables. If you using javascript/jquery usually you need to check if the variable given is not empty, nulled, or undefined before using it to your function. Because if you don't validate your variables it could cause an error to your javascript code.

 

Check empty variable

In this example, I have an if statement in javascript that will check the variable is empty.

var a = '';

if(a == ''){
  console.log('Empty');
}

 

Check null variable

In this example, it will check the nulled variable before executing it.

var a = 'codeanddeploy';

if(a == null || a == NULL){
  console.log('Nulled');
}

 

Check undefined variable

As you can see below, I used typeof() function in javascript to determine variable data type.

if(typeof a == "undefined"){
   console.log('undefined');
}