In JavaScript in the browser window
is the global object, which means every variable defined in the global scope is a child of window
. So why do I get this result:
console.log(window.foo); // No error, logs "undefined".
console.log(foo); // Uncaught ReferenceError: foo is not defined.
Those two lines should be the same, shouldn't they?
Because with
window.foo
you are explicitly looking forfoo
property ofwindow
object which is not the case in latter option. In the latter option, iffoo
isn't defined, you should as developer be able to know that it isn't defined and get the clear error warning rather than interpreter setting it toundefined
on its own (like first case) which will lead to unexpected results.Reference Error:
Take a look at this article for more info:
Quoting from above article:
Examples:
References which are neither properties or variables are by definition unresolvable and will throw a ReferenceError, So: