Analysis of local variables and global variables in javascript and javascript
Recently, I have a group of questions about the interview and basic knowledge about global variables and local variables:
Fun foo (){
Var a = B = 0;
}
Let's select the values of a and B separately. Maybe we don't take a closer look. We may think of a and B as local variables. The value is 0. In fact, a is a local variable, B is a global variable. This is mainly because the operator priority from right to left is the same as that of the css selector that we usually Parse in the browser, a higher priority is expression B = 0. At this time, B is not declared, and the return value of the expression is 0. It is assigned to the local variable a declared by var, as shown below:
Var a = (B = 0 );
If all the variables with chained values are declared, unexpected global variables will not be created, such
Function foo (){
Var a, B;
A = B = 0; // both are local variables
}
Global variables created using var (these variables are created outside the function) cannot be deleted;
You can delete the hidden global variables created without using var (though embedded in the function;
Although variable declaration can be anywhere in the document, it is a good habit to declare variables before all JavaScript code and initialize and assign values to variables. The variable is also declared inside the function and then referenced.
In variable query, accessing local variables is faster than global variables, because you do not need to search for the scope chain. Local variables are automatically cleared and destroyed when the function is executed, without occupying the memory, all variables are automatically destroyed only when the window page is closed. Therefore, we usually try to use local variables to reduce global variables and reduce environmental pollution.