ReferenceError and global object

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

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

Fiddle

These two lines should be the same, right?

+6
source share
3 answers

Because with window.foo you are explicitly looking for the foo property of the window object, which does not apply to the last option. In the latter case, if foo not defined, you, as a developer, should know that it is not defined, and get a clear error warning, not the interpreter, setting it to undefined yourself (for example, in the first case), which will lead to unexpected results.

Link Error :

Represents an error when referring to a nonexistent variable. When you try to dereference a variable that has not been declared, a ReferenceError is raised.

Take a look at this article for more information:

Quote from the article above:

A link is considered unsolvable if its base value is undefined . Therefore, a reference to a property is unsolvable if the value up to the point is undefined. In the following example, you will throw a ReferenceError, but it is not, because a TypeError gets there first. This is because the base value of the property obeys CheckObjectCoercible (ECMA 5 9.10 through 11.2.1), which throws a TypeError when trying to convert the Undefined type to an object.

<strong> Examples:

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

Links that are neither properties nor variables are, by definition, unsolvable and will raise ReferenceError, So:

 foo; //ReferenceError 
+17
source

In the first example (window.foo), you access the property of the window object. JavaScript returns "undefined" when you try to access an object that does not exist. It is designed that way.

In the second example, you reference the variable directly, and since it does not exist, an error occurs.

This is how JavaScript is designed and works.

+2
source

In JavaScript, you can assign object fields on the fly like this, so window.foo almost (see comments below) equivalent to var foo; if it is defined in a global context, then just calling foo browser panic, because it does not even know which object to look at. Notice if you do this:

 //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" 
+1
source

Source: https://habr.com/ru/post/912914/


All Articles