Difference Between Undefined And Null In JavaScript


This blog explains the differences between Undefined and Null. I am going to explain both the types while working with JavaScript. It is very important to know when we get a variable as undefined and when do we get it as null. 
Here, I will take a small example to make it clear to the developers why they get a variable as 'undefined' and 'null'. It is very important before performing any action on the variable, that we check if a variable is null or not because if we try to perform any action on null, then it will throw an exception. Let us start the meaning of both with this example.
This means that the variable is not declared or variable is declared but the value is not assigned.
For example,
  1. var test;  
  2. alert(test); //undefined   
  3. alert(typeof test); //undefined  
In the above code, we are able to see that the variable named "test" is not assigned any value. So, it means that JavaScript considers the variable as undefined. If we check with an alert, it will give undefined. We can check the type of the same variable, which is also undefined because the "test" variable is never assigned a value. So, the unassigned variables are considered as undefined, by default.
It means the variable is assigned with a null value.
For example,
  1. var test= null;  
  2. alert(test); //null  
  3. alert(typeof test); //object  
In the above code, we are able to see that the "test" variable is assigned with the null value. When we check it with an alert, it will return null and the type of that variable will give "object".
How to check if a variable is undefined or null? 
check undefined  variable
  1. typeof variaible === "undefined"  
check null variable
  1. variable === null  
Equality operator considers both as equal.
  1. null == undefined // true  
Identity not considered as equal,
  1. null === undefined // false  


In this article, we learned two important things that are very useful while working with JavaScript. The key point to remember is that in JavaScript, undefined is type, and a null is an object.