When testing for the existence of a variable you should never blindly test with that variables name. The same rings true when finding properties and methods of deeply nested objects.
With that in mind:
// error will occur if someObj has not ever been defined in your code.
if (someObj) {
// someObj has been defined
}
You can workaround that and use minimal code by testing against the global scope, which in browsers it is the window level.
// safe way to test for global variable.
if (window.someObj) {
// someObj has been defined
}
Another fine test for global variable would be using the builtin typeof method, however it gets a bit tedious to type out if you have to do it often enough.
// another safe method for testing a global variable
if (typeof someObj != "undefined") {
// someObj has been defined
}
Now for the testing of deep nested objects (often used as pseudo-namespaces in JS).
// testing deep nested object
if (self.someObj &&
someObj.something &&
someObj.something.foo &&
someObj.something.foo.bar) {
// do something ...
}
Just two final quick notes for advanced coders:
Sometimes in IE I've noticed that doing that type of lookup / existence test has actually called the method if I was testing for it. eg:
// this is an example, I can't recall which actual methods did this off-hand
if (document.execCommand) {
// resultant value of execCommand method gets used to pass/fail the conditional
}
And, finally a very mild side-effect of these type of existence lookups is that when you have a getter applied to that property, it will actually run the getter during the conditional testing.
// this code only runs in Firefox 2+
// and is provided for instructional purposes only
var foo = {
get bar() { alert("bar getter was executed") }
};
if (foo.bar) {
// a foo.bar property is defined
}