How to understand global and local variable in javascript

1st test:

var a = 1; function b() { a = 10; return; function a() {} } b(); alert(a); // 1 

Second test:

 var a = 1; function b() { a = 10; return; } b(); alert(a); // 10 

In the first test, a is 1 , although I set it to 10 in the method. In the second test, I set it to 10 , and it was set to 10 when I output it. How it works?

+4
source share
4 answers

Function declaration function a() {} declares the name of the variable a in the local area of ​​your function b (and assigns it a function). When you assign a , you assign this local variable not global.

When using lift your code is equivalent

 var b = function b() { var a = function a() {}; a = 10; return; } var a = 1; b(); alert(a); // 1, obvious now 
+2
source

Since lifting creates a local variable a , which masks the global one before trying to assign a value to it.

+2
source

In your first test, you create a function that is stored in the local a variable:

 function b() { a = 10; return; function a() {} // can be called using a() inside this function } 

So you can call this function using a() inside your b() function. Try:

 function b() { a(); // alerts "hi" a = 10; return; function a() { alert("hi"); } } 

Now you save the number 10 in the local variable instead of the function. The global variable remains unchanged, so your external warning still shows 1.

0
source

The first example is interpreted (JavaScript) as:

 var a = 1; function b() { var a = function () {}; a = 10; return; } 

In JavaScript, all local variables (in this case, the local variable a, which will hold the function) are declared at the top of the function.

The local variable a gets the value 10, not the global one. Then it ceases to exist after returning.

0
source

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


All Articles