JS function scope

Scope of a function

JavaScript is used in the scope of the function, the variables declared in the body of the function thereof as well as any function of the body is the body of the function definition of the nested

ES6 standard scope 

Why block-level scope

Global scope and function scope, not block-level scope, prone to the following questions:

1) lift variable variables may cause the inner cover layer variables

  1.  
    where i = 5;
  2.  
    function func() {
  3.  
    console.log(i);
  4.  
    if (true) {
  5.  
    where i = 6;
  6.  
    }
  7.  
    }
  8.  
    func(); // undefined

2) the loop variable for counting leakage global variables

  1.  
    for (var i = 0; i < 10; i++) {
  2.  
    console.log(i);
  3.  
    }
  4.  
    console.log(i); // 10

ES6 standard block-level scope

'Block-level scope' is achieved by the new command and let const, will be introduced in the future

Guess you like

Origin www.cnblogs.com/CWJDD/p/11030901.html