2

I am really confused about this code

var box = document.getElementsByClassName('box-value');

for(let i = 0; i < box.length; i++){
    box[i].onclick = function(){
        console.log(i);
    }
    console.log("End loop. i:" + i);
}

let i = 0;
box[i].onclick = function(){
    console.log(i);
}
i = 9;

box[0].onclick();

enter image description here

In the first block, i is 0

enter image description here

But in the second block, i is 9.

I really don't understand why?

Haris Long
  • 21
  • 2

2 Answers2

2

Because your first i is in a block and doesn't get changed afterwards, while your second i (is not in a block) and does get set to 9 before the click handler is run. You can emulate the behaviour from the loop by doing

{
    let i = 0; // one variable that stays constant
    box[i].onclick = function(){
        console.log(i);
    };
}
let i = 9; // a different variable

and you can also emulate the altering behaviour of the assignment by putting the scope around the loop:

let i = 0;
for(; i < box.length; i++) {
    box[i].onclick = function() {
        console.log(i);
    };
    console.log("End loop. i:" + i);
}
Community
  • 1
  • 1
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
2

The i declared with let in the for loop won't exist after the loop ends. The second i is separate and you setting that to 9, that's why the value of the second i is 9.

let statement documentation

TrampolineTales
  • 808
  • 3
  • 14
  • 31
mstrdruid
  • 21
  • 2