Students Empire

Learn Something New
Home

Under Defined Type


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.

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

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.

				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.