Haris Long
Haris Long

Reputation: 29

Let in Javascript. Confusion

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?

Upvotes: 2

Views: 112

Answers (2)

mstrdruid
mstrdruid

Reputation: 21

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

Upvotes: 2

Bergi
Bergi

Reputation: 664297

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);
}

Upvotes: 2

Related Questions