CodeSteps

Python, C, C++, C#, PowerShell, Android, Visual C++, Java ...

JavaScript – 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.

Let’s see the below example:

var i = 10;
typeof i;

number

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;
undefined

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:

i==undefined;
false
k==undefined;
true

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;
object

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

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

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

.Paul.

JavaScript – About “null” and “undefined” types

Leave a Reply

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

Scroll to top