ReferenceError and the global object

gdoron is supporting Monica picture gdoron is supporting Monica · Apr 11, 2012 · Viewed 9.3k times · Source

In javascript window is the global object, which means every object in the global scope is a child of window. So why I get this result:

console.log(window.foo); // No error, logs "undefined".
console.log(foo);        // Uncaught ReferenceError: foo is not defined.

Fiddle

Those two lines should be the same, shouldn't they?

Answer

Sarfraz picture Sarfraz · Apr 11, 2012

Because with window.foo you are explicitly looking for foo property of window object which is not the case in latter option. In the latter option, if foo 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 to undefined on its own (like first case) which will lead to unexpected results.

Reference Error:

Represents an error when a non-existent variable is referenced. A ReferenceError is thrown when trying to dereference a variable that has not been declared.

Take a look at this article for more info:

Quoting from above article:

A Reference is considered unresolvable if its base value is undefined. Therefore a property reference is unresolvable if the value before the dot is undefined. The following example would throw a ReferenceError but it doesn’t because TypeError gets there first. This is because the base value of a property is subject to CheckObjectCoercible (ECMA 5 9.10 via 11.2.1) which throws a TypeError when trying to convert Undefined type to an Object.

Examples:

var foo;
foo.bar; //TypeError (base value, foo, is undefined)
bar.baz; //ReferenceError (bar is unersolvable)
undefined.foo; //TypeError (base value is undefined)

References which are neither properties or variables are by definition unresolvable and will throw a ReferenceError, So:

foo; //ReferenceError