And let a little problem on the var

Disclaimer: This article is a blogger original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
This link: https://blog.csdn.net/litcangosh/article/details/101356877

Today in learning JS, inadvertently found some minor problems regarding var and let, I understand my record, pointing chiefs also want to see it, look at the code directly.

        for(var i=0;i<5;i++){
        	
            function f() {
                console.log(i);//5
            }  
        }
        console.log(i);//5
         f();
  1. Print out the results here is 5, because i is declared by the variable var, global variables, inside the console.log i i points to a global variable, the loop does not execute the function declaration only when the loop is finished, the ES5 standard JS is not block-level scope, so when the loop ends, and i did not destroy, (only global variables in a page is closed only destroy) this time i was 5, then called f (), and then perform the function f , the value of i is 5
      	for(let i=0;i<5;i++){
         
            function f() {
                console.log(i);//4
            }  
        }
         f();
  1. The use let to declare variables, the results of the answer is four.
    Let command variables declared within a block of code is only useful where the let command, let the variable i is declared, the current i is only valid in the current round of cycle, each cycle of i in fact a new variable defined in the ES6, wheni=4When the code inside the execution cycle, after ++ i ,, i = 5 i = 5 when the loop has ended, this time with the end of cycle i has been destroyed, the block-level scope final state is i 4, so when calling the function, the final result is 4.

Added: AO function after each execution objects (called the execution context object or function-scoped objects) have been destroyed under normal circumstances, and are generating new AO objects each execution.

Guess you like

Origin blog.csdn.net/litcangosh/article/details/101356877