Global variables are added as properties of the global object, which is window in a browser. To test if an object has a property or not, use the in operator:
// In global scope
var bar;
function foo() {
if (bar in window) {
// bar is a property of window
} else {
// bar isn't a property of window
}
}
For more general code, the environment may not have a window object, so:
// In global scope
var global = this;
function foo() {
if (bar in global) {
// bar is a property of the global object
} else {
// bar isn't a property of the global object
}
}
Beware of typeof tests. They only tell you the type of the variable's value and return undefined if either the property doesn't exist or its value has been set to undefined.
window.ashould reference the global variable, but I've never done this (re-using the same variable name in different scopes) so I don't know about the potential caveats.