Difference between null and undefined in JavaScript


In this article you will learn difference between null and undefined in JavaScript. In previous article we have explained about data types in JavaScript. Basically null and undefined are data types in JavaScript i.e. both are Primitive data types. Data types specify the value of the variable that is string, number, boolean, object, array etc. To find the type of variable, we use typeof operator in JavaScript.

null in JavaScript

Basically null is the data type in JavaScript. Null represents null i.e. no value at all. Null is a type of object.

let x = null
console.log(x) // null
console.log(typeof(x)) // object

In the above code we have seen x variable has a null value and type of this variable is object. So null is object type.

undefined in JavaScript

Undefined means not a value. Suppose we have declared a variable but not assigned a value to this variable then this variable is undefined.

let x;
console.log(x) // undefined
console.log(typeof(x)) // undefined

let x = undefined;
console.log(x) // undefined
console.log(typeof(x)) // undefined

In the above code we have seen x variable doesn’t have any value i.e. undefined. The type of the variable is also undefined.

Suppose we want to access non exist property from an object then they return also undefined like as below code.

let x = {}
console.log(x.name) // undefined

Here we have access the non exist property from x object then it returns undefined value.

If we want to compare null and undefined with equal operator (==) then they returns true but it returns false when we compare using strict equality comparison operator (===).

console.log(null == undefined) // true
console.log(null === undefined) // false

Actually equality comparison operator (===) also check the type of the variable. The type of null is object and type of undefined is undefined. So equality comparison operator (===) returns false.

So in this article we have learned difference between null and undefined in JavaScript.
If you want to improve this article or you find anything wrong/incorrect in this article then please leave a message using below comment box.

Leave a Reply