The difference between let and VaR in ES6 for loop

Time:2020-8-2

Let is different from var

for(var i=0;i<5;i++){
  setTimeout(()=>{
    console.log (i) ; // five 5
  },100) 
}
console.log(i);//5
console.log('=============')

for(let j=0;j<5;j++){
  setTimeout(()=>{
    console.log(j);//0,1,2,3,4
  },100) 
}
console.log (j) ; // error J is not defined

Why can let display the correct result, but not var?

VaR is a global scope, which has the function of variable promotion. Therefore, defining a variable in for can be used globally. Every time a value is assigned to a variable I in the loop, it is assigned to the global variable I.

Let is a block level scope, which can only work in code blocks. In JS, a statement in {} is also called a code block. Each loop will generate a code block, and each code block contains a new variable J;

Isn’t it said in ES6 that let declared variables cannot be declared repeatedly? Here’s an example:


{
  let a=123;
}
{
  let a=246;
}
console.log(a);//a is not defined;
{ 
  var b=1;
}
{ 
  var b=2;
}
console.log(b);// 2;

{} represents a block. At this time, the variables declared by let only work in this block, but this block does not affect the variables declared by var. Because VaR is a global scope.

let a=1;
let a=2;
//Uncaught SyntaxError: Identifier 'a' has already been declared
//Let cannot be declared repeatedly

let b=1;
var b=2;

// Uncaught SyntaxError: Identifier 'a' has already been declared
//Let cannot be declared repeatedly


var c=3;
var c=4;
console.log (c) // 4; VAR can be declared repeatedly

The above is the whole content of this article, I hope to help you in your study, and I hope you can support developeppaer more.