|
JavaScript has a built-in operator called typeof that you can use to determine whether a variable has a value or is "undefined." The code/**
* Enum of types compatible with typeof.
* @enum {String}
* @private
*/
goog.JsType_ = {
UNDEFINED: 'undefined',
NUMBER: 'number',
STRING: 'string',
BOOLEAN: 'boolean',
FUNCTION: 'function',
OBJECT: 'object'
};
/**
* Returns true if the specified value is not |undefined|.
* WARNING: Do not use this to test if an object has a property. Use the in
* operator instead.
* @param {Object} val Variable to test
* @return {Boolean} Whether variable is defined
*/
goog.isDef = function(val) {
return typeof val != goog.JsType_.UNDEFINED;
};ExampleTODO Further reading
|
Isn't it straightforward to simply test "typeof val === 'undefined'"?
The whole "enum" definition only makes sense if you have access to a JavaScript? type-checking tool (which is not universally available yet.)
val === undefined is the simplest way of testing if the variable is undefined. Are there any compatibility issues?
alot of the "constants" in javascript are in fact not constant, perhaps this is intended to sidestep that by storing a good version of it early in case something insane occurs and undefined gets overwritten.
You can simple write:
if (window.val) // It's true if val is defined.
if (window.val) also evaluates to false if val is zero, null, false or an empty string. You really do need to explicitly check whether it's undefined.
Simply referencing an undefined variable (without the typeof keyword) will throw an error. If you reference it through an object (the window object represents the global namespace), it will instead be undefined.
The undefined global 'constant' isn't really constant. Any script running on your page can set it to an arbitrary value, so it shouldn't be trusted. You can make your own trusted constant, by using the otherwise useless void keyword, or executing a function with no return value:
var UNDEFINED = void 0; // void [any value] yields undefined. Useful, eh? var UNDEFINED = (function(){})();When comparing against it, be sure to use the '===' operator. '==' does type coercion and can give you unexpected results:
If you're doing a lot of undefined checks, this method will be faster, since it does not require a string comparison