The life cycle of a variable is also called scope, which refers to the valid range of a variable in the program. According to scope, variables can be divided into global variables and local variables.
1. The scope of global variables is global, that is, global variables are everywhere in the entire javaScript program.
2. Variables declared inside a function only work inside the function. These variables are local variables and their scope is local; the parameters of the function are also local and only work inside the function.
I often see articles on the Internet saying: "There are two ways to declare global variables in Javascript: 1. Do not use the var keyword when declaring variables. 2. Declare variables outside the function. When using the first method to declare variables, even Inside the function, the variable is still a global variable. When using the second method to declare a variable, even if the var keyword is used, the declared variable is also a global variable." Test it yourself and you will know whether it is right or wrong: see the following example:
2 var v01 = "I am a global variable v01"; // Global variables declared using VAR keywords
3 v02 = "I am a global variable v02" "; / /Global variables not declared using the var keyword
4 function fun1(){
5 alert(v01); //output "I am a global variable v01"
6 alert(v02); //output "I am a global variable v02 "
7
8 v03 =" I am a global variable v03 ";
9 var v04 =" I am a local variable v04 "; "I am the global variable v01"
14 "I am the global variable v02"
15
16 alert(v03); //error: "v03 is not defined"
17 alert(v 04); / /error: "v04 is undefined"
1