Undefined property or variable in JavaScript

  sonic0002        2014-07-24 06:56:07       11,675        0    

JavaScript is a weak type language, and also you can use a variable or property where it's undefined. If we don't have correct ways to check whether a property or variable is defined, we may get unexpected results when we try to access the,. How can we check whether a property or variable is undefined?

This is actually a somewhat tricky question. Let's start off with some facts about undefined and then see what kind of function is consistent with the ones we care about.

  1. JavaScript attaches types to values, not variables. Values can have type undefined; variables either exist (if declared) or they don't (if not).
  2. All variable declarations are initialized with a value whose type is undefined. This is not the same as other languages such as Java. Java properties have a value of null when they are declared. In JavaScript, until they're assigned any other value. the values will be undefined
  3. Variables that aren't declared do not have undefined values—they just don't exist at all. Trying to dereference one will raise a ReferenceError unless you use the typeof operator.
  4. When applied to an undeclared or undefined-valued variable, typeof returns the string "undefined".
  5. null == undefined but null !== undefined. It might be tempting to treat them as equivalent, but they really do mean different things.
  6. Don't assume it's safe to compare things with a value named undefined. It's not a reserved word, so all your comparisons will break if someone redefines it. (You can prevent that problem by declaring an uninitialized variable named undefined, overwriting it yourself in case somebody else did.)
  7. For objects, accessing a property that hasn't been attached will return undefined. You might see an error raised if you try to do something with it, like calling it as a method, but just accessing it is usually fine as long as the object itself exists.
  8. Since accessing a property that doesn't exist and a property with value undefined gives you the same result, using the typeof or equality operators is not enough to tell undefined properties apart from nonexistent ones. For that we can use in, which returns true if the object has the property and false if it doesn't, or Object.hasOwnProperty(), which does the same thing but doesn't look in the prototype chain.

With all that in mind: The simplest way to check for undefined is to use typeof, ignoring the possibility of ReferenceErrors since that's almost always just a coding mistake.

// Note that this doesn't quite work for objects
function isUndefined(value) {
    return typeof value === 'undefined';
}

var a, x = 4;

isUndefined(a); // true

isUndefined(x); // false


To check for undefined valued object keys, you could do something like this:

key in obj && typeof obj.key === 'undefined';
// - or -
obj.hasOwnProperty(key) && typeof obj.key === 'undefined';


Depending on what exactly you mean by an object's property being undefined, you could write the check in function form with something like the example below. In this case, "undefined" means key is either nowhere in the object and its prototype chain or key is present with value undefined

/**
 * Returns true if key is not a key in object or object[key] has 
 * value undefined. If key is a dot-delimited string of key names,
 * object and its sub-objects are checked recursively.
 */
function isUndefinedKey(object, key) {
    var keyChain = Array.isArray(key) ? key : key.split('.'),
    objectHasKey = keyChain[0] in object,
    keyHasValue = typeof object[keyChain[0]] !== 'undefined';

    if (objectHasKey && keyHasValue) {
        if (keyChain.length > 1) {
            return isUndefinedKey(object[keyChain[0]], keyChain.slice(1));
        }  
        return false;
    }else {
        return true;
    }
}

var undefined,
     ponies = {
        pretty: false,
        scummy: true,
        favorite: {
            food: 'money'
        },
        goodFor: undefined
    };

isUndefinedKey(ponies, 'pretty'); // false
isUndefinedKey(ponies, 'goodFor'); // true
isUndefinedKey(ponies, 'anyValueWhatsoever'); // true
isUndefinedKey(ponies, 'favorite.food'); // false

You may also be interested in knowing how to check whether an object is an array or not.

Reference: Bulat Bochkariov

JAVASCRIPT  ARRAY  PROPERTY  UNDEFINED 

       

  RELATED


  0 COMMENT


No comment for this article.



  RANDOM FUN

Android developer vs iOS developer