To record the timing of JS execution, take a few examples. It’s a little confusing.

🌰 1:

let a = 1
function fn(){
  console.log(a)
}
Copy the code

Print out how many? 1? ❌

But it does not print because no function is called.

🌰 2:

let a = 1
function fn(){
  console.log(a)
}
fn()
Copy the code

Print out how many? 1? ✅

One more call than in the previous example, printing 1.

🌰 3:

let a = 1
function fn(){
  console.log(a)
}
a=2
fn()
Copy the code

Print out how many? 1? ❌

Declare the variable a and assign it to 1, declare the function fn and assign 2 to a, call fn and print a with a value of 2.

🌰 4:

let a = 1
function fn(){
  console.log(a)
}
fn()
a=2
Copy the code

Print out how many? 1? ✅

Instead of the previous example, fn first prints a as 1 and assigns 2 to a.

From the above examples, we can conclude that to determine the result of the function execution, we need to pay attention to the code before the function execution time. Since the following code has not been executed, it does not affect the result of the function.

Let’s look at some more asynchronous examples: 🌰 5:

let a = 1
function fn(){
    setTimeout(()=>{console.log(a)},0)
}
fn() // 2
a = 2
Copy the code

SetTimeout executes after a while, assigning 2 to a before printing the value of a.

Take a look at a classic interview question, convenient view I mark a 🌰 6:

let i = 0
for(i = 0; i<6; i++){
  setTimeout(()=>{
    console.log(i)
  },0)
}
Copy the code

What is the result of I?

The answer is six sixes, declaring that I is a global variable with only one value of I. In the whole process, setTimeout is not executed when I satisfies the conditional loop. Finally, when the condition is satisfied, the value of I is 6, and setTimeout is executed for 6 times to print out A, so the result is 6 6.

What if I want to print out 0,1,2,3,4,5? See 🌰 7 below:

for (let i = 0,i<6,i++){
  setTimeout(()=>{
    console.log(i)
  },0)
}
Copy the code

Because let declarations in for are local variables that follow block scope, each time the for loop executes, a separate scope is generated and a new I is generated, equivalent to six I’s. Each time setTimeout() is executed, the corresponding I is printed, and the result is 0, 1, 2, 3, 4, 5.

One last example,

function f1(){
  let a = 1
  function f2(){
    let a = 2
    function f3(){
      console.log(a)
    }
    a = 22
    f3()
  }
  console.log(a)
  a = 100
  f2()
}
f1()
Copy the code

How many will be printed at the end? It’s 1 and 22.