What is the JavaScript undefined Data Type?

By: Dusty Arlia
Published on Tuesday, March 26, 2013, 06:33 PM
Last Updated on Saturday, July 18, 2015 at 6:50 PM
Total Updates: 4

undefined is the value of a variable with no value. This happens when you declare a variable, but never assign a value to it (initialize it). You can also get the undefined value returned when you use an object property that does not exist.

The Internet Explorer Developer Center explains how you can test variables to see if they exist or if they have the undefined data type. Here is a snippet from their webpage:

You can check to see if a variable exists by comparing it to undefined, although you can check if its type is undefined by comparing the type of the variable to the string "undefined". The following example shows how to find out if the variable x has been declared:

var x;

// Testing the value of x. This method works. 
if (x == undefined) {
    document.write("comparing x to undefined <br/>");
}
.
// Testing the data type of x. This method doesn't work - you must check for the string "undefined".
if (typeof(x) == undefined) {
    document.write("comparing the type of x to undefined <br/>");
}
// Testing the data type of x. This method does work. 
if (typeof(x) == "undefined") {
    document.write("comparing the type of x to the string 'undefined'");
}

// Output: 
// comparing x to undefined 
// comparing the data type of x to the string 'undefined'

If you would like to test the value of property p in object o, do this:

o.p !== undefined   //evaluates to true if o has a property p

References

Data Types (JavaScript). (2013). Retrieved March 26, 2013, from
http://msdn.microsoft.com/en-us/library/ie/7wkd9z69(v=vs.94).aspx

Comments:

Ad: