0

Im confused why this code works

for(let i=12;i<=80;i++){
  let emjoi = document.querySelector(`#em${i}`);

   emjoi.addEventListener("click",() => {
    console.log(i);
    result 12 13 14 15 16 17 18 19 20 21 right though to 80
    });

 }

but if i do it this way without using let it only gives me the end value at the end of the loop

for(i=12;i<=80;i++){
let emjoi = document.querySelector(`#em${i}`);

emjoi.addEventListener("click",() => {

console.log(i);

result 81

});

}
Harry
  • 521
  • 7
  • 21
ross
  • 1
  • 1
    Yes this is an aspect of JavaScript that is very annoying but let solves the scoping issue. I think it's because the event listener function is being invoked somewhere completely different than where it's defined in the source code? – Richard Bamford Feb 14 '20 at 22:05
  • Its weird because i thought that when you use a varible without let or var it is global does addeventlister create its own scope – ross Feb 14 '20 at 22:10
  • yes I think so, JavaScript is very annoying like this :) glhf – Richard Bamford Feb 14 '20 at 22:12
  • 1
    [JavaScript closure inside loops – simple practical example](https://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example) – 3limin4t0r Feb 14 '20 at 22:56
  • @ross It is global, that's why the variable is the same for all callbacks. Since event listeners are callbacks, the loop gets executed before any callback is actually called. When the loop finishes the final value of the variable is still set. All callbacks refer to this same variable (containing the final loop value). – 3limin4t0r Feb 14 '20 at 22:59

0 Answers0