1. Variables
ECMAscript variables are loose variables. The so-called loose variables mean that the variable name can save any type of data. Each variable is just a placeholder for saving a value.
Definition: var firstDemo;
2. Scope of variables
2.1 Basic Concepts
Use var to define variables: define local variables in the scope of the variable. This method of defining variables is also called an explicit declaration.
If you don’t understand this, you can take a look at the simple and crude example below:
As can be seen from the above two examples, if you use var to define a variable in a function, the variable will be destroyed after the function exits.
Omit var to define a variable: As long as the function that defines the variable is called once, the variable can be accessed in the global scope. This method of defining variables is also called implicit declaration
Clearing the scope of variables can help us think about how to declare variables reasonably, which not only reduces unnecessary memory overhead, but also largely avoids the trouble caused by repeated definitions of variables overwriting previously defined variables. .
2.2 Scope Analysis
Output result:
A、0 0 1 0
B、0 undefined 1 0
C, 0 error i is not defined
You can guess which result will be, and the reasons will be explained in detail in the message.
The above is the entire content of this article. Simply put, the scope of variables in any programming language is a very critical detail. The scope of variables in JS is more free compared to languages such as JAVA and C. A big feature is that JS variables do not have block-level scope, and variables in a function are valid in the entire function.