Javascript check if object property exists, even when object is undefined

javascript, oop, underscore.js

Solution

You can use the "short circuit" `&&` operator:

if (myObject && myObject.myProperty) { 
    ...
}

If `myObject` is "falsey" (e.g. undefined) the `&&` operator won't bother trying to evaluate the right-hand expression, thereby avoiding the attempt to reference a property of a non-existent object.

The variable `myObject` must have course already have been declared, the test above is for whether it has been assigned a defined value.

Problem

I want to check if an object exists, and has a property. Currently I get a "myObject is undefined" error that stops the check. How can I make the following still work correctly even when myObject may not exist? ``` if (myObject.myProperty) { ... } else { ... } ``` I am trying to just even check if a object / variable exists but getting an error: `if (foo) { console.log('hello'); }` gives the error Uncaught ReferenceError: foo is not defined. Here is a jsfiddle http://jsfiddle.net/cfUss/

Original source