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);
}
}
}
There are 4 elements in the list. Outputs of the 3 functions:
first: 4 4 4 4
second: 0 1 2 3
third: 0 1 2 3
I am not able to understand the output from the third function. In the second function, each call to the IIFE creates a new function object and hence, a new val variable. But in the third function, there is a single copy of the variable x, then how is the output: 0 1 2 3
Please correct me if I am wrong.
let
, it's only defined in the scope it's created in. Theitems.length
number of anonymous functions all refer to difference instances ofx
because you defined it withlet
.let
works "as expected" within closures when used to initialize afor
loop is an exception to the normal semantics oflet
, not a consequence of them.const
is also scoped to its block, but we can't dofor (const a = i; a < n; a++)
- this will raise an error on the second loop iteration because we're trying to assign a value to an already-initializedconst
.let
andconst
are both scoped to the containing block, butlet
also has a special behaviour insidefor
loops that scopes it to the loop iteration instead of to the block.let
is scoped to the block but that it's scoped to the iteration. Technically the iterator variable isn't even being defined in the block; it's being defined in the loop construct, and how those bindings work goes on a case by case basis. Personally I find the inconsistency betweenlet
andconst
surprising and counterintuitive. The only reason we can't useconst
to initialize afor
loop is that there is only one binding for the loop. Then they go and give us multiple bindings if we uselet
instead!