block-level scope nodejs

Now let us understand the three keywords var, let, const, characteristics and use.

where

JavaScript, we usually say that the scope is function scope, variables var statement, regardless of where in the code is declared, will be promoted to the top of the most current scope, this behavior is called variable lift (Hoisting)

That is, if the variable is declared inside a function, will be promoted to the beginning of the function, while in the variable declared globally, it will elevate to the top of the global scope.

 

function test() {
    console.log('1: ', a) //undefined
    if (false) {
      var a = 1
    }
    console.log('3: ', a) //undefined
}

test()

 

The actual implementation, the above code variables in a function will be raised to the top of the statement, even if the condition of the if statement is false, the same does not affect a variable lift.

Test function () { 
    var A 
    // A statement is not assigned 
    the console.log ( '. 1:', A) // undefined 
    IF (to false) { 
      A =. 1 
    } 
    // no assignment statement A 
    console.log ( '3:' , A) // undefined 
}

  In scene function nested functions, variables, only recently elevated to the top of a function, but will not upgrade to the external function.

// b raised to the top of the function a, but will not improve the function test. 
    Test function () { 
        function A () { 
          IF (to false) { 
            var B = 2 
          } 
        } 
        the console.log ( 'B:', B) 
    } 

    Test () // B IS Not defined

  If a statement does not, then it will error, no assignment is not the same after the statement and no statement, this point must be separate areas, help us find a bug

// a declaration of no case 
    a is not defined

  let

const can be declared and let block-level scope, and usage is similar to var, let the characteristic variable is not lifting, but is locked in the current block.

A very simple example:

Test function () { 
        IF (to true) { 
          the console.log (A) // of TDZ, commonly known as the temporary dead zone, the variables used to describe the phenomenon does not enhance 
          the let A =. 1 
        } 
    } 
    Test () // A IS Not defined 

    function Test () { 
        IF (to true) { 
          the let A =. 1 
        } 
        the console.log (A) 
    }     
    Test () // A IS Not defined

  The only correct way to use: the first statement, and then visit.

function test() {
        if(true) {
          let a = 1
          console.log(a)
        }
    }
    test() // 1

  

 

Guess you like

Origin www.cnblogs.com/danruoyanyun/p/11390157.html