What is undefined type in Javascript

Description

The Undefined type has only one value, undefined. When a variable is declared without initialization, it is assigned the value of undefined:


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

In this example, the variable message is declared without initializing. When compared with the literal value of undefined, the two are equal.

The code above 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 any uninitialized variable gets the value of undefined.

The undefined value is provided mainly for comparison.

The code above generates the following result.

undefined value vs undefined variable

A variable containing undefined value is different from an undefined variable.


var aString;     
console.log(aString);           //"undefined"
console.log(anotherValue);      //causes an error

An undefined variable is using a variable name before its definition.

In this example, the first line displays the variable aString, which is "undefined".

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





















Home »
  Javascript »
    Javascript Introduction »




Script Element
Syntax
Data Type
Operator
Statement
Array
Primitive Wrapper Types
Function
Object-Oriented
Date
DOM
JSON
Regular Expressions