The JavaScript undefined Property

An undefined variable is a variable that has not been declared or that it has an undefined value (i.e. the variable has not been initialised).

The JavaScript undefined global property indicates that a variable has not been assigned a value. The initial value of the global variable undefined is the primitive value undefined.

The following are examples of variables that are undefined:

foo; // throws an error, foo is not defined (undeclared)
var foo; // foo is undefined (uninitialised)

Functions also return undefined when they don't return a value (i.e. they are of type void).

undefined vs. null

JavaScript has another similar special value called null. Unlike undefined, null means that the variable is defined and that it's value is null. In other words, undefined means that the value of a variable is not known, while null means that the variable doesn't have a value but it is known that it has no value.

When undefined is compared to null for equality, the result is true. However, they are not identical, as the following example demonstrates:

if (foo == null) { // true (test for equality)
	// code that gets executed
}
if (foo === null) { // false (test for identity)
	// code that never gets executed
}

A variable that has not been assigned a value is of type undefined, while a variable that has been assigned the value null is of type object.

Testing for defined and undefined variables

Relying on the undefined property is not entirely safe to check if a variable is undefined. undefined is a variable in the global scope that can be re-assigned another value at any time:

undefined = "whatever";
if (foo === undefined) {
	// never gets executed
}

As such, it is safer to use the typeof operator to test whether a variable has been assigned a value:

if (typeof foo == "undefined") {
	// do something
}

If you see a typo, want to make a suggestion or have anything in particular you'd like to know more about, please drop us an e-mail at hello at diveintojavascript dot com.

Copyright © 2010-2013 Dive Into JavaScript