JavaScript -- the difference between using var and let to declare variables in a for loop

1. var in for() loop

We first create an array and assign values to each item of the array with the for() loop. The conditional expression of the for loop is declared with var:

let arr = [];

for (var i = 0; i < 5; i++) {
	arr[i] = function() {
		console.log(i);
	}
	
	arr[i](); // Called immediately with each loop
}

The following results are obtained

On this basis, we call the first item of the array after each loop:

let arr = [];

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

give the result as follows

As the for() loop goes on, the variable i increases continuously, and the i in each print statement of the array also changes.
At the end of the loop, we call each item in the array separately

let arr = [];

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

arr.forEach((total) => {
	total();
});

give the result as follows

After the loop ends, the value of variable i is 5, and i in each print statement of arr is 5

that is because
When declared with var, the variable i is unique, and each change of i changes its own stack address.
Therefore, when accessing i after the loop ends, the basic quantity pointed to by i is obtained through the stack address stored last time.
After the loop ends, we can still access the variable i externally:

let arr = [];

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

that is because
After the loop ends, the variable i declared by var is not destroyed, and we can still get the corresponding value by accessing i
To verify that the i we access externally is the i in the for() loop, we change the value of i externally, and then access it through an array:

let arr = [];

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

i = 8;

arr.forEach((total) => {
	total(); // 8 8 8 8 8 
});

console.log(i); // 8

2. let in for() loop

Let's use the same method to see how the i declared by the let is different
We still let each cycle print the value of the first item

let arr = [];

for (let i = 0; i < 5; i++) {
	arr[i] = function() {
		console.log(i);
	}
	arr[0](); // 0 0 0 0 0
}

As the variable i increases, i in the first print statement of the array is always 0. Because the stack address of the first item i is no longer changed, and it is fixed to the constant 0.
i is also different in other items of the array, but a variable cannot hold multiple addresses at the same time.
This shows that i is different in each item of the array, and they store different stack addresses. In each cycle, there will be a new i to store the new address. Each new variable i is based on the previous variable i.
We call each item in the array after the loop is finished and access the variable i externally.

let arr = [];

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

arr.forEach((total) => {
	total(); // 0 1 2 3 4 
});

console.log(i); // error: i is not defined

After the for() loop, each item of the array can still print different values, and the value of variable i cannot be accessed externally.
In other words, the i variable for the user cannot be accessed, and the i variable that the user can use has been destroyed.
The call of each item of the array can still print normally. These different i in the array should be saved by the browser in a special way, and we are denied direct access.

let and var in the for loop

for(var i=0;i<5;i++){
        setTimeout(function(){
            console.log(i);
        },0)
    }
// Result 5 5 5 5 5
1
2
3
4
5
6
for(let i=0;i<5;i++){
        setTimeout(function(){
            console.log(i);
        },0)
    }
// Result 0 1 2 3 4

Explanation found online:
Among the three statements for, the first statement: i=0, is executed before the start of the loop code block, and each loop will be executed.
Due to the variable promotion mechanism of the var command, the var command will actually be executed only once.
The let command does not have variable promotion, so each loop will be executed to declare a new variable (but the initialized value is different).
Each loop of for has a different block level scope, and the variables declared by let are block level scope, so there is no problem of repeated declaration.
In the for loop of the let life variable, each anonymous function actually refers to a new variable

Keywords: Javascript html5

Added by zigizal on Fri, 17 Dec 2021 10:45:22 +0200