Google News
logo
Full Stack Developer - Interview Questions
How null is different from undefined in JavaScript?
Null : Null means a variable is assigned with a null value. If we use it with typeof operator it gives result as an object. We should never assign a variable to null because the programmer uses it to represent a variable that has no value. Note that JavaScript will never automatically assign the value to null.
 
Undefined : Undefined means the variable is declared but not assigned any value to it. It may be a variable itself does not exist. If we use it with typeof operator it gives the result undefined. It is not valid in JSON.
 
Let's understand it through an example.
var var1  
var var2 = null //assigning null value to the variable var2  
console.log(`var1 : ${var1}, type : ${typeof(var1)}`)  
console.log(`var2 : ${var2}, type : ${typeof(var2)}`)  
When we execute the above code, it generates the following output :
Var1 : undefined, type : undefined  
var2 : null, type : object  
From the above output, we can observe that the value of var1 is undefined also its type is undefined. Because we have not assigned any value to the variable var1. The value null is assigned to the variable var2. It prints its type as abject. Since null is an assignment value and we can assign it to a variable. Therefore, JavaScript treats null and undefined relatively equally because both represent an empty value.
Advertisement