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 accessed by all scripts; the variables defined in the function are local variables, and local variables are only valid within the function.
If the global variable and the local variable use the same variable name, the local variable overrides the global variable.
Example code:
<! DOCTYPE html>
The result of the operation 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:
If you use Var, the program forces a new variable to be defined.
If Var is not used, the system will first search for the variable in the current context and redefine a new variable only if it does not exist.
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 an already covered local variable A, but does 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