Analyzing classic interview questions: let var in for loop

For more articles, you can check out my blog: https://icheng.github.io/

topic

In the for loop, using var or let to declare the i variable will result in different results.

var arr = [];
for (var i = 0; i < 2; i++) {
    
    
      arr[i] = function () {
    
    
        console.log(i);
      }
}
arr[0]();
arr[1]();

Output:
2
2

var arr = [];
for (let i = 0; i < 2; i++) {
    
    
      arr[i] = function () {
    
    
        console.log(i);
      }
}
arr[0]();
arr[1]();

Output:
0
1

why is that?

analyze

First of all, we all know the global scope and local scope of js

global scope

var is declared outside the function and belongs to the global scope
, which means:
there is only one i variable globally

if (true) {
    
    
   var name = '123';
}
console.log(name);  // 输出 '123'

local scope

Variables declared by let belong to the local scope,
which means:
the variable is valid within { }

if (true) {
    
    
   let name = '123';
}
console.log(name);    // 没有定义

What happens when defining var in for loop

Each time through the loop, function is added to the array, function is

function () {
    
    
  console.log(i);
}

Because var is used to define the i variable, there is only one i globally.
Therefore, in each round of the loop, the global i is increased.
After exiting the loop, i = 2

final execution

arr[0]()
arr[1]()

Execute the corresponding function

console.log(i);

So the output:

2
2

So the key is:
the function is executed last. At this time, the function looks for the current global variable i, which is 2

Insert image description here

What happens when defining let in a for loop

The Red Book describes it this way: Because let is used to define variable i, during each iteration loop, the JS engine will declare a new iteration variable in the background.
Therefore: for each console.log(i), the referenced i is different. variable instance

Insert image description here

When the function is finally executed, the variable i of its own block scope is used,
so the output is:

0
1

So the key is:
each loop will have variable i in its own block-level scope { } and ultimately reference different variable instances.

Guess you like

Origin blog.csdn.net/weixin_52268321/article/details/132564243