It's important to be cautious when testing for the existence of a variable. Simply checking if the variable exists by its name can lead to errors, especially when dealing with deeply nested objects.
To avoid potential issues, consider the following approach:
// Check if someObj is defined to prevent errors
if (someObj) {
// someObj is defined
}
Instead of directly checking against the variable, you can test against the global scope, which is often represented by the window object.
// Safe way to test for a global variable
if (window.someObj) {
// someObj is defined
}
Another reliable method is to use the typeof operator to check if a variable is not undefined.
// Another safe method to test for a global variable
if (typeof someObj != "undefined") {
// someObj is defined
}
When dealing with deeply nested objects, such as pseudo-namespaces in JavaScript, you can test their existence like this:
// Testing deeply nested objects
if (self.someObj &&
someObj.something &&
someObj.something.foo &&
someObj.something.foo.bar) {
// Do something...
}
For advanced coders, here are a couple of quick notes:
In some cases, performing existence tests in Internet Explorer may inadvertently trigger the method being tested.
// Example that may call the method in IE
if (document.execCommand) {
// The result of execCommand method is used to evaluate the conditional
}
Additionally, be aware that using getter functions in conditional testing can actually trigger the getter to run.
// This code demonstrates the effect of getter in conditional testing
var foo = {
get bar() { alert("bar getter was executed") }
};
if (foo.bar) {
// A foo.bar property is defined
}