In the documentation for the let
statement in MDN, there's this example code:
var list = document.getElementById("list");
for (let i = 1; i <= 5; i++) {
let item = document.createElement("li");
item.appendChild(document.createTextNode("Item " + i));
item.onclick = function (ev) {
console.log("Item " + i + " is clicked.");
};
list.appendChild(item);
}
Then they state:
The example above works as intended because the five instances of the (anonymous) inner function refer to five different instances of the variable i.
I do not understand why there are "five different instances of the variable i
.
The first statement in a for
loop is always executed once, no?
So the let
statement is supposed to only execute once...
Once the code reaches the end of the iteration it checks the condition in the second statement.
How come, according to what they write, there's a new instance of i
on each iteration?