Things defined outside the function body are global variables, and those defined inside the function body are local variables. The definition here refers to the declaration through var.
JavaScript has the concept of implicit globals, which means that any variable you do not declare will become a global object property. For example:
The two results are the same, indicating that myname is a global variable.
So, is there any difference between implicit global variables and explicitly defined global variables? . The answer is definitely yes, look at the example below:
As can be seen from the above example: global_test1 defined by var outside the function cannot be deleted, and global_test2 and global_test3 that are not defined by var are deleted (regardless of whether they are created within the function body).
In summary, global variables declared through var outside the function cannot be deleted, but implicit global variables can be deleted.
It should be noted here: JavaScript has a behavior called "hoisting" (suspending/top parsing/pre-parsing).
Let’s illustrate with an example:
Do you think the contents of the two alerts are the same? ? Obviously inconsistent, needless to say consistent. . Actual output is: "undefined", "local_huming".
The above example is equivalent to
The myname output by the first alert is not the global variable you think, but a local variable in the same scope (a function body) with it. Although it has not been declared, it is treated as such. This is called "hoisting".
This should make it clear. When you use a variable in a function body and redeclare it later, an error may occur.
Writing specifications:
The benefits are:
1. All local variables are defined at the beginning of the function for easy search;
2. Prevent logical errors when variables are used before they are defined.
Have you understood the variable declaration of JavaScript? The above content is very detailed and easy to understand. The final summary is also very pertinent. Don’t miss it.