Difference between Undefined & Null in JavaScript

In JavaScript undefined & null sound like same, but they are different.

undefined

If you make a variable and don’t assign a value, javascript interpreter by default will show undefined.

let a;
// undefined

As soon as a variable has been declared the value undefined attached with that variable until we assign something to it.

let a
// the value of a is undefined
a = 10
// the value of a is 10 now

null

null means no value. If you want to assign a variable with nothing you can use null.

let a = null

We can’t do any operation with it as it is nothing but an empty value.

5 + null
// 5
5 - null
// 5

The type of null and undefined are not same

typeof undefined
// "undefined"
typeof null
// "object"

This tells us null & undefined can’t be same if you consider based on their type.

Leave a Comment

Your email address will not be published. Required fields are marked *