ReferenceError and the global object

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.

Fiddle

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


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:

  • Understanding JavaScript’s ‘undefined’

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

In your first example (window.foo) you are accessing a property of the window object. JavaScript returns "undefined" for when you are trying to access a non existent property of a object. It's designed that way.

In the second example you are referencing a variable directly, and since it does not exists an error is raised.

It's just the way JavaScript is designed and works.


In JavaScript you can assign object fields on the fly like that, so window.foo is nearly (see comments below) equivalent to var foo; when defined in the global context, whereas just calling foo out of the blue makes the browser panic 'cause it down't even know which object to look in. Notice, if you do:

//when in global context, 'var' sets a property on the window object
var foo;

console.log(foo);
//it will then also log `undefined` instead of throwing the error.

//if you then do:
foo = "abbazabba";

console.log(window.foo);
// it will return "abbazabba"