0

I am having a hard time understanding this code below -

const aTag = document.querySelectorAll("a")
for(var i=0;i<aTag.length;i++) {
  aTag[i].addEventListener('click',function onClick(e) {
   e.preventDefault();
   console.log("I",i)
  })
}

This gives me 6 every time i click a tag. But as soon as i replace var with let the tag which is clicked that index is returned. I get it that the closure function has same reference to i for var but for let a new copy of i is created. I still dont understand why this happens. Can someone explain why?

Shweta
  • 305
  • 1
  • 3
  • 17

0 Answers0