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?

6
  • 2ality.com/2015/02/es6-scoping.html#let-in-loop-heads Commented Apr 2, 2017 at 12:52
  • @trincot I don't think that duplicate applies here Commented Apr 2, 2017 at 12:54
  • 1
    What part don't you understand? What logs would you have expected instead? Commented Apr 2, 2017 at 12:54
  • 1
    @Bergi The question isn't the same but this answer also covers let in for loops. Commented Apr 2, 2017 at 12:56
  • @Bergi, I have anyway removed the duplicate... just in case the use of let and block scope deserves a separate answer here. Commented Apr 2, 2017 at 13:15

2 Answers 2

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);
}
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.