Because with window.foo
you are explicitly looking for the foo
property of the window
object, which does not apply to the last option. In the latter case, if foo
not defined, you, as a developer, should know that it is not defined, and get a clear error warning, not the interpreter, setting it to undefined
yourself (for example, in the first case), which will lead to unexpected results.
Link Error :
Represents an error when referring to a nonexistent variable. When you try to dereference a variable that has not been declared, a ReferenceError is raised.
Take a look at this article for more information:
Quote from the article above:
A link is considered unsolvable if its base value is undefined . Therefore, a reference to a property is unsolvable if the value up to the point is undefined. In the following example, you will throw a ReferenceError, but it is not, because a TypeError gets there first. This is because the base value of the property obeys CheckObjectCoercible (ECMA 5 9.10 through 11.2.1), which throws a TypeError when trying to convert the Undefined type to an object.
<strong> Examples:
var foo; foo.bar; //TypeError (base value, foo, is undefined) bar.baz; //ReferenceError (bar is unersolvable) undefined.foo; //TypeError (base value is undefined)
Links that are neither properties nor variables are, by definition, unsolvable and will raise ReferenceError, So:
foo;
source share