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.fooyou are explicitly looking forfooproperty ofwindowobject which is not the case in latter option. In the latter option, iffooisn'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 toundefinedon 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: