This snippet results in a JavaScript runtime error: (foo
is not defined)
if (foo) {
// ...
}
I have to define foo
I sense you are asking because you are aware that javascript seems to allow undefined variables in some situations (ie no runtime errors) and not in others.
The reasoning is as follows: javascript always throws an error on checking undefined variables, but never throws an error on checking undefined properties, as long as you only use one level of indirection.
Example:
// throws runtime error
if(foo) {
// ...
}
// does not throw runtime error
if(window.foo) {
// ...
}
// does not throw runtime error
var obj = {};
if(obj.foo) {
// ...
}
// throws runtime error
if(obj.foo.bar) { // going two levels deep, but foo is undefined
// ...
}
Hope that clears it up a bit.