In JavaScript, depending on the scope of the variables are divided into local variables and global variables, the directly defined variables are global variables, global variables can be all the script access; the variables defined in the function are local variables, and local variables are only valid within the function.
Assuming that the global and local variables use the same variable name, the local variable overrides the global variable.
Sample code:
<! DOCTYPE html>
The result of the implementation is this:
Click Test1 to eject the local variable.
Click Test2, eject Undefined, and then pop the local variable
Click Test3, pop up the global variable, and then pop the local variable
This is where the difference between using VAR and not being used is:
Assuming that Var is used, the program enforces a new variable.
Assuming that no Var is used, the system will first search the current context for the existence of the variable, and will only define a new variable once again without being present.
TEST3, the variable a used is a global variable, the first direct output of the global variable, the second is directly assigned to the global variable after use.
The use of Var in test1 and test2 to define new variables with the same name will cause the variables in the function to overwrite the global variables. So in Test2: the first output of a is already covered by the local variable A, but did not give the initial value, so there will be undefined this result. Using variables in this way is actually wrong and you should avoid them.
Incorrect use of Var in javascript causes undefined