In the example code from 'let' keyword javascript reference @ Mozilla Developer network from section Cleaner code in inner functions:
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);
}
This code's description from underneath the sample states, that [...]Note that it does not work as intended if you replace let with var, since all of the inner functions would then return the same final value of i: 6[...].
I've checked this in webconsole, instead of #list (which I couldn't find in this document) I've targeted #quick-links ol, so var list = document.getElementById("quick-links").children[1];
.
During first test, I pasted into js console opened for that document this sample, with changed target element - so #quick-links ol and run.
Result was seen at the bottom of left sidebar, SEE ALSO quick links. When clicked on dom element Item x, event script put text "Item x was clicked".
Second test, instead of let used var, and same event scripts printed text "Item 6 was clicked", no matter what item I've clicked on.
Why such behaviour? I know slightly the difference between let and var, but why i in case of var in loop is assigned to inner function only with value 6?