Understanding undefined in Javascript


Understanding undefined in Javascript

Interesting thing about variable handling in Javascript is there is no type information associated to a variable. Ex,

var anoop=1;

Here variable anoop is of number type. But, since Javascript has loose typing so we can associate anoop variable to string type.

anoop="hello javascript";

What I wanted to say is in Javascript variable can be associated to any data type and the variable’s data type is bound to the data type of the value. I guess you know the process of declaration and definition of variable in a language. Declaration is when you create a new variable, and definition is when you assign a value to a variable. So, after grabbing these concepts let me know the data-type of below variable in Javascript world.

var rai;

It will print undefined.

Well we know that data-type of variable depends on data-type of value, but here there is no value, just a declaration, no definition. When a Javascript variable is between the declaration and definition stage then the data-type of variable is undefined and the value is also undefined. Well like boolean data-type has 2 values true and false, likewise undefined data-type has only one value and that is undefined. During declaration in Javascript a value is automatically assigned to the variable and it’s undefined, and the data-type of the variable is undefined.

So basically there are 5 primitive types in Javascript as per ECMAscript5 specs.

  • number
  • string
  • boolean
  • undefined
  • null

About Anoop Kumar Rai