Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 208
gdoron is supporting Monica Avatar asked Apr 11 '12 08:04

gdoron is supporting Monica


1 Answers

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
like image 163
Sarfraz Avatar answered Nov 09 '22 04:11

Sarfraz