JavaScript – The difference between UNDEFINED and NULL

JavaScript - The difference between UNDEFINED and NULL

Many programmers who are starting out with JavaScript find it difficult to understand the difference between “NULL” and “UNDEFINED”. In this post, we will go through each of these data types in detail.

UNDEFINED:

When a variable is declared, but no value is assigned to that variable then that variable will be of type undefined. For example,

var demoVar;
console.log(demoVar);

The above code will output undefined to the console, since variable demoVar is declared but not assigned with a value.

Also, undefined is of type “undefined”.

var demoVar;
console.log(typeof demoVar);

The above code will output “undefined” to the console.

NULL:

NULL means lack of existence of a value. NULL value needs to be explicitly assigned to the variable. For example,

var demoVar = null;
console.log(demoVar);

The above code will output null to console, since variable demoVar is manually assigned with null value.

Null can be considered as a placeholder value. A null value is assigned to variable to indicate that variable is empty at the current stage of program but will hold a value later on.

Unlike undefined, the type of null value is an object.

var demoVar = null;
console.log(typeof demoVar);

The above code will output “object” to the console.

Summary:

  • Undefined means variable is declared but no value is assigned to that variable.
  • NULL is a placeholder. It indicates that variable is intentionally assigned with an empty value.

I hope now you understand the difference between NULL and UNDEFINED in JavaScript. If you have any query or feedback feel free to leave a comment.

Leave a Reply

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