The difference between Javascript global variables var and non var is explained in depth

  • 2020-03-30 00:47:15
  • OfStack

I believe that you are familiar with global variables, in the function scope with the form of a=1 defined variables will be a global variable, in the global scope, with the following three forms can be created to create a globally visible name:

var a = 1;
b = 2;
window.c = 3;

For b=2, which is essentially the same as c, when you execute this assignment statement, you go down the scope chain looking for a variable called b, you go to the top of the scope chain and you haven't found it yet, so you add a property b to the window and you assign it.

There are two differences between var and non-var:

The global variable of 1 var cannot be deleted, because delete intelligently deletes the deletable property of the object, and the global property defined by var is marked as undeletable. To be clear, an unsuccessful delete does not throw an error, and the return value of delete is true|false.

2 global variables defined by var will be promoted, while global variables not defined by var will not be promoted. You can see the results of the following program:

var a=1;

alert(a);//error, a undefined

Related articles: