Difference between null and undefined in JavaScript

JavaScript null and undefined :

We often got confused with null and undefined in javascript. In this blog post, I will explain to you in simple words with an example. The difference is same for both Javascript and Typescript.

Main difference :

undefined means you have declared one variable but haven’t assigned any value to it or the variable itself doesn’t exist. But null means that the variable is assigned with a value null. For example :

var first_var
var second_var = null

console.log(`first_var : ${first_var}, type : ${typeof(first_var)}`)
console.log(`second_var : ${second_var}, type : ${typeof(second_var)}`)

It will print the below output :

first_var : undefined, type : undefined
second_var : null, type : object

As you can see that the value of firstvar_ is printed as undefined and its type is also undefined, because we haven’t defined any value to the variable.

But for secondvar, it is printed as _object for its type and null as its value.

So, null is an assignment value and we can assign it to a variable.

How to check null and undefined :

For the below example :

var first_var
var second_var = null

console.log(first_var == null)
console.log(second_var == null)
console.log(first_var == undefined)
console.log(second_var == undefined)

The output is :


So, either it is null or undefined, javascript treates them equal. We can use anyone of them in a conditional block.