Discussion on the scope of Javascript variables

  • 2020-05-05 10:57:31
  • OfStack

Variable scope problems in Js :

1. No block-level scope. Variables in Js are not scoped with {}, unlike C/C++/Java.

Such as:


 if(true){
     var name = "qqyumidi";
 }
            
 alert(name);  // Results: qqyumidi

Js adds variables defined in if to the current execution environment, especially when using for loops.


 for(var i=0; i<10; i++){
     ;
 }
 
 alert(i);   // Results: 10

Here is only personal understanding, if there is a mistake, please let us know.


Related articles: