2

I will like to understand how it determines the exactly clicked arrow and show its remaining content. My expectation is that the loop is supposed to be complete and i is expected to be equal to the final index of the array. What exactly is happening at the time of the click event?

let answer = document.querySelectorAll(".answer");
let arrow = document.querySelectorAll(".arrow");

for (let i = 0; i < arrow.length; i++) {

 /* prompt(i); */

  arrow[i].onclick = function() {
  arrow[i].classList.toggle("active");
  answer[i].classList.toggle("active");
  }
}
OJay
  • 63
  • 1
  • 6
  • The loop you have, sets an onclick event on each element found. nothing more. Then when you click on one of those elements, it fires the function attach to it . – G-Cyrillus Apr 16 '22 at 06:22
  • *"My expectation is that the loop is supposed to be complete and i is expected to be equal to the final index of the array."* That's very reasonable, and it's what you would have gotten with `var`. But most people didn't expect that and it was the source of endless bugs for people. When they added `let` to JavaScript, they gave it block scope, and very cleverly decided that *each loop iteration* would have its own block scope and its own copy of `i`. So there's a separate `i` for each loop iteration, and thus for each click handler to close over. See the linked question's answers for more. – T.J. Crowder Apr 16 '22 at 06:25
  • 2
    (I also cover this in detail in Chapter 2 of my recent book *JavaScript: The New Toys* about the additions to JavaScript in ES2015-ES2020. Links in my profile if you're interested.) – T.J. Crowder Apr 16 '22 at 06:26
  • I kind of understand the difference between var and let scopes. But what I don't get is how it's chained to each click and was able to determine them.? For example: at the time of click i = arrow[arrow.length - 1] If I clicked the first element which is arrow[0]. I don't expect the code to work but it does. That's where my confusion is. What am I missing? – OJay Apr 16 '22 at 06:50
  • @Ola-Juwon - It's what I said above: There's a **different** `i` for each loop. The `i = 0` of the first loop is never changed. Instead, at the beginning of the second loop, and new `i` is created and assigned the value of the previous one, then the `i++` is done on that new `i`. Then the loop with `i = 1` runs, and *that* `i` never changes. Each function closes over the block scope where it was created, so each function closes over a different `i` variable. – T.J. Crowder Apr 16 '22 at 06:55

0 Answers0