alert(a); // undefined alert(...">

When I use a global scope variable without "var", it shows me an error. What for?

See my sample code below

<script> alert(a); // undefined alert(b); // It is Error, b is not defined. var a=1; b=10; </script> 

When a and b are in global scope, why do I get an error message for b. But for variable a there is no error message? what is the reason?

can someone explain to me?

+6
source share
1 answer

The first alert shows undefined because var statements go up to the top of the nested area, in other words, var and function statements are declared before the code actually executes, at the parsing stage.

When your code executes, it is equivalent to:

 var a; // declared and initialized with `undefined` before the code executes alert(a); // undefined alert(b); // ReferenceError, b is not declared. a=1; b=10; 

The second alert is not even executed, an attempt to access b gives you a ReferenceError , because you never declared it, and you are trying to access it.

The way the identifier resolution process works in Javascript, if the identifier is not found in the entire scope chain, a ReferenceError exception is thrown.

In addition, you should know that assigning an identifier without declaring it first (like b = 10 ) does not technically declare a variable, even in the global scope, the effect can be similar (and it seems to work), at the end the identifier ends as a property global object, for example:

 var a = 1; b = 10; // Similar effect: window.a; // 1 window.b; // 10 

But this is only due to the fact that the global object is the highest record in the environment chain of visibility areas.

Another difference between the two above: the identifier declared with var creates an unconfigurable property for the global object (it cannot be deleted), for example:

 delete window.a; // false delete window.b; // true 

In addition, if you are in the scope of a function and assign an undeclared identifier, it will be a property of the global object, as in the above example, while the var statement will create a local variable, for example:

 (function(){ var a = 1; b = 10; })(); typeof window.a; // 'undefined', was locally scoped in the above function typeof window.b; // 'number', leaked, an unintentional global 

I would really be discouraged by assignments to undeclared identifiers, I always use var to declare your variables, moreover, it was forbidden in strict ECMAScript 5 mode, assignments to undeclared identifiers throw a ReferenceError :

 (function(){'use strict'; b = 10;})(); // throws a ReferenceError 
+12
source

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


All Articles