Js global variables and local variables
This article is a summary of your own learning.
A simple definition of global variables and local variables: all variables declared outside the function are global variables, and those declared in the function are local variables.
I. duplicate names of local variables and global variables overwrite global variables.
1 var a = 1; 2 function test1() { 3 var a = 2; 4 alert(a); 5 } 6 test1();// 2
Here, the function defines a as a local variable. Its scope is between functions {}, and a defined outside the function is a global variable, its scope is the entire program (the description is a bit inaccurate ). In the function, the local variable and the global variable are duplicated. The local variable overwrites the global variable.
2. One point that must be explained when we mention global variables and local variables isVariable increase(This is a pitfall ). 'Unlike C/C ++, The JS engine is used to obtain all declared variables and then execute them one by one, all variable declaration statements are promoted to the header of the current code block '. Note: A code block refers to a {} of a function. Normally, the variables in the {} of if, while, and for are not upgraded.
After learning about the variable upgrade, we use the following code to demonstrate it:
1 var a = 1; 2 function test1() { 3 alert(a); 4 var a = 2; 5 alert(a); 6 } 7 test1(); 8 alert(a);//undefined 2 1
Why is the result not 1 2 1? The reason is that the Code is upgraded. The Code actually executed is as follows::
1 var a = 1; 2 function test1 () {3 var a; // global variables are overwritten when the names of local variables and global variables are duplicated, at this time, only the declaration of a has not defined 4 alert (a); // Therefore, the execution of alert value is undefined 5 a = 2; 6 alert (a); 7} 8 test1 (); 9 alert (a); // undefined 2