Javascript - Data Types Undefined Type

Introduction

The Undefined type has only one value, which is the special value undefined.

When a variable is declared using var but not initialized, it is assigned the value of undefined as follows:

var message; 
console.log(message == undefined);    //true 

The variable message is declared without initializing it.

When compared with the literal value of undefined, the two are equal. This example is identical to the following:

var message = undefined; 
console.log(message == undefined);    //true 

Here the variable message is explicitly initialized to be undefined.

This is unnecessary because, by default, any uninitialized variable gets the value of undefined.

A variable containing the value of undefined is different from a variable that hasn't been defined at all.

Consider the following:

var message;     //this variable is declared but has a value of undefined 
console.log(message);  //"undefined" 
console.log(age);      //causes an error 

In this example, the first alert displays the variable message, which is "undefined".

In the second alert, an undeclared variable called age is passed into the console.log() function, which causes an error because the variable hasn't been declared.

Only one useful operation can be performed on an undeclared variable: you can call typeof on it (throws an error in strict mode).

The typeof operator returns "undefined" when called on an uninitialized variable, but it also returns "undefined" when called on an undeclared variable.

Consider this example:

var message;     //this variable is declared but has a value of undefined 
console.log(typeof message);  //"undefined" 
console.log(typeof age);      //"undefined" 

In both cases, calling typeof on the variable returns the string "undefined".

It is good practice to initialize variables.

So that, when typeof returns "undefined ", you'll know that it's undeclared variable.