In JavaScript, depending on the scope of the variable's function, divided into local 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 valid only within the function.
If global and local variables use the same variable name, local variables will overwrite global variables.
Example code:
The result of the run is this:
Click Test1 to eject the local variable.
Click Test2, eject Undefined, and then eject the local variable
Click Test3, pop the global variable, and then eject the local variable
That's where the difference between using Var and not using it 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 existence of the variable in the current context, and redefine a new variable only if it does not exist.
In Test3, the variable A is a global variable, the first time the global variable is directly exported, and the second is used directly after the global variable is assigned a value.
In Test1 and Test2, a new variable with the same name is defined using Var in a function, which causes the variables in the functions to overwrite the global variable. So in Test2: the first output of a is a local variable A that has already been overwritten, but the initial value is not given, so there is a undefined result. The use of variables in this way is actually wrong and should be avoided.