Difference Between Null and Undefined in JavaScript

Introduction

 
Sometimes we check a variable is null or undefined in JavaScript to avoid error. Suppose a variable is null and we are trying to perform some action on it then it throws error. So before performing any action on variable we need to check null – it is useful when you think that variable might be null in some scenario. Some developers say "You can avoid null error by checking a variable is undefined". Now a question arise in mind that “What is difference between null and undefined”. Let’s discuss:
 
Undefined
 
In JavaScript, declare a variable and no value is assigned to it. Now the variable is undefined.
Declare a variable name and nothing is assigned to the name variable. Then alert the variable gives undefined as result.
  1. var name;  
  2. alert(name); // undefined  
  3. alert(typeof(name)); // undefined  
Null
 
In JavaScript null is nothing. That means something is assigned to variable which doesn’t have any value. Data type of null is object.
 
Declare a variable assign and assign null value to it. Now alert the variable which returns null as result and alert typeof of null which returns object as result.
  1. var name = null;  
  2. alert(name); // null  
  3. alert(typeof(name)); // object  
Let's take another example in which we create two variables obj1 and obj2. In obj1 we don't assign anything but in obj2 we assign a blank object. Now we try to access value of obj1.test which throws you exception that cannot read property but in obj2.test gives you undefined as result. Here is the code:
  1. var obj1;  
  2. var obj2= {};  
  3. alert(obj1.test); // Throw you exception as cannot read property of undefined  
  4. alert(obj2.test); // undefined  
Now compare between undefined and null value: 
  1. if(null === undefined) // false  
  2. if(null == undefined) // true  
  3. if(null === null// true  
From above discussion undefined and null are two distinct types: undefined is a type itself (undefined) while null is an object.
 

Conclusion

 
In this blog we discussed the difference between null and undefined in JavaScript. Hope it helps you to understand how and where we need to use null and undefined in JavaScript.