Global and Local Variables of JavaScript

  • 2021-06-28 08:38:14
  • OfStack

1. JavaScript scope is divided by function function blocks, not if, while, for.


<script>
function f1(){
   alert("before for scope:"+i);    
 //i Not assigned (not declared!Using undeclared variables or functions can cause fatal errors that interrupt script execution) 
 // here i Value is undefined
   for ( var i=0; i<3;i++){
       alert("in for scope:"+i);}
 //i The value of is 0 , 1,2  
   alert (" after for scope " +1);
  //i The value of is 3 At this point for scope Outside, but i The value remains as 3
    while ( true ) {
       var j=1;
       break;}
    alert(j);
  //j The value of is 1 At this point while scope Outside, but j The value remains as 1
    if ( true ) {
      var k=1;
    }
    alert(k);
  //k The value of 1 At this point if scope Outside, but k The value remains as 1
}
f1();
// At this point, the function is called outside the function block, and the output exists again f1 this function scope In i j k variable 
alert ( i ) ;
//error!!! The reason is here i Not declared (not unassigned, difference) f1 Of 1 Line Output), Script Error, Program End! 
alert ( j);    
// unexecuted 
alert ( k ; 
// unexecuted 
</script>

2. JavaScript precompiles the entire script file before execution (parses the declaration part of the script file, including the local variable part) to determine the scope of the real variable.An example is below:


<script>
   var x=1;
   function f2(){
    alert(x);
   //x The value of undefined !this x Not a global variable because function scope Has been declared again 1 Local variable with duplicate names, so global variable parameters a Covered. 
     Explanation JavaScript It is precompiled before execution, and the x Is pointed to a local variable, not a global variable.here x Notice only, no assignment, so is undefined
    x=3;
    alert(x);
   //x Value is 3. But it's still a local variable 
    var x;
   // local variable x Statement here 
    alert(x);
   // Value is 3
   }
   f2();
   alert(x);
   //x Value is 1 Not in function scope Internal, x The value of the is the value of the global variable. 
</script>

3. When a global variable is renamed with a local variable, the scope of the local variable overrides the scope of the global variable. After leaving the scope of the local variable, it returns to the scope of the global variable. When a global variable encounters a local variable,

How do you use global variables?Use window.globalVariableName.


<script>
   var a=1;
    function f3(){
       alert(window.a);
  //a position 1 Here's the a Is a global variable 
       var a=2;
        alert(a);
      }
    f3();
    alert(a);
</script>

Related articles: