Udostępnij za pośrednictwem


Undefined Values

In JScript, you can declare a variable without assigning a value to it. A type-annotated variable assumes the default value for that type. For example, the default value for a numeric type is zero, and the default for the String data type is the empty string. However, a variable without a specified data type has an initial value of undefined and a data type of undefined. Likewise, code that accesses an expando object property or an array element that does not exist returns a value of undefined.

Using Undefined Values

To determine if a variable or object property exists, compare it to the keyword undefined (which will work only for a declared variable or property), or check if its type is "undefined" (which will work even for an undeclared variable or property). In the following code example, assume that the programmer is trying to test if the variable x has been declared:

// One method to test if an identifier (x) is undefined.
// This will always work, even if x has not been declared.
if (typeof(x) == "undefined"){
   // Do something.
}
// Another method to test if an identifier (x) is undefined.
// This gives a compile-time error if x is not declared.
if (x == undefined){
   // Do something.
}

Another way to check if a variable or object property is undefined is to compare the value to null. A variable that contains null contains "no value" or "no object." In other words, it holds no valid number, string, Boolean, array, or object. You can erase the contents of a variable (without deleting the variable) by assigning it the null value. Note that the value undefined and null compare as equal using the equality (==) operator.

Note

In JScript, null does not compare as equal to 0 using the equality operator. This behavior is different from other languages, such as C and C++.

In this example, the object obj is tested to see if it has the property prop.

// A third method to test if an identifier (obj.prop) is undefined.
if (obj.prop == null){
   // Do something.
}

This comparison is true

  • if the property obj.prop contains the value null

  • if the property obj.prop does not exist

There is another way to check if an object property exists. The in operator returns true if the specified property is in the provided object. For example, the following code tests true if the property prop is in the object obj.

if ("prop" in someObject)
// someObject has the property 'prop'

To remove a property from an object, use the delete operator.

See Also

Reference

null Literal

undefined Property

in Operator

delete Operator

Other Resources

JScript Variables and Constants

Data in JScript

JScript Data Types

Data Types (Visual Studio - JScript)