function first(){
var items = document.getElementsByTagName("li");
for(var x = 0; x < items.length; x++){
items[x].onclick = function() {
console.log(x);
}
}
}
function second(){
var items = document.getElementsByTagName("li");
for(var x = 0; x < items.length; x++){
(function(val) {
items[val].onclick = function() {
console.log(val);
}
})(x);
}
}
function third(){
var items = document.getElementsByTagName("li");
for(let x = 0; x < items.length; x++){
items[x].onclick = function() {
console.log(x);
}
}
}
The list contains four elements. The results of the three functions:
first: 4 4 4 4
second: 0 1 2 3
third: 0 1 2 3
I'm puzzled by the output from the third function. In the second function, a new function object is created with each IIFE call, resulting in a new 'val' variable. However, in the third function, there is only one instance of the variable x, so why do we get: 0 1 2 3
If I've misunderstood something, kindly correct me.