JavScript: About “null” and “undefined” types

JavaScript supports different types of data types. JavaScript has dynamic types. That means, the type of the variable is come to know depending on the value the variable holds. What happened if the variable is not assigned with any value? Good, we don’t know the type of the variable. Hence “undefined” type.

If the variable is declared and its type is unknown JavaScript return “undefined” type for that particular variable.

Lets see the below example:

var i = 10;
typeof i;

The variable “i” is declared and assigned with the value 10. When we use “typeof i;” statement, JavaScript returns “number” type, because the value 10 is number.

Then we don’t assign anything to the variable and use “typeof” statement to check the type of the variable. Below is the example:

var k;
typeof k;

Observe that JavaScript returns “undefined” type if the variable’s type is unknown.

We can use “undefined” in conditional statements also. Lets check our variables “i” and “k” are defined or not. To check this we can use “undefined” value type. Below is the example:


Observe that we have defined the variable “i”. So, the first statements return “false”. In the second statement we are not defined the variable “k”; hence JavaScript returns “true”.

Then, why we need “null”?

In JavaScript, “null” is a built-in object, and it indicates there is no value. Whereas “undefined” indicates there is no type.

typeof null;

If we want to unset the value of a variable, we can use “null”.

var msg="Hello, World!";
if ( msg == null )
   print('Message not set');

Note: All these JavaScript statements are tested in jconsole. You can access jconsole from here.


Leave a Reply