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.
- var name;
- alert(name);
- alert(typeof(name));
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.
- var name = null;
- alert(name);
- alert(typeof(name));
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:
- var obj1;
- var obj2= {};
- alert(obj1.test);
- alert(obj2.test);
Now compare between undefined and null value:
- if(null === undefined)
- if(null == undefined)
- if(null === null)
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.