Data Types in JavaScript : NULL & Undefined

NULL is a value. You assign this value to the variable or object to wipe out all the data in it.

undefined is itself NOT a value (it represents lack of value/data). When variable or object doesn’t have even a NULL or blank/empty (“”) values then JavaScript says, it is undefined.

Undefined is forced by JavaScript runtime when variable or object data is not present and you are trying to use it.

NULL is not always forced by JavaScript. You will get NULL because you have assigned object or variable NULL intentionally or because of missing data from source.

Undefined not gives you any choice. You have to assign data to the variable or object before using it.

You cannot explicitly SET any variable or object as undefined. You only GET undefined from JavaScript runtime.

NULL gives you choice. You can explicitly SET any variable or object to NULL. Also, if there is a mistake in code or data you will GET NULL from JavaScript runtime.

Let’s see Examples.


let flag;

In the above example you can see we have declared flag variable BUT not assigned any value/data to it. On the next line we are using variable flag to display data in it.

You will get undefined in the console log. Which is forced by the JavaScript runtime. Basically it is saying that, “There is no value/data inside the variable. If you want to use the variable then define some value/data in it”.


let flag;
flag = null;

In the above example, We have assigned NULL value to the flag variable. So, you will get NULL in the console log.

That’s it. We hope you get some idea regarding NULL and undefined.

Categories js

Subscribe Now!

Subscribe Us For Latest Articles