JavaScript JavaScript and the DOM Responding to User Interaction Listening for Events with addEventListener()

Michael Mersiades
Michael Mersiades
12,920 Points

Why does the for loop in the code in this video never end?

Normally, a JavaScript for loop will start when the line with "for" on it is executed, and will keep looping through the code until some exit condition is met, at which point the for loop will end.

But this for loop seems to last forever. Please help me to understand what is going on here.

Antti Lylander
Antti Lylander
9,659 Points

I recommend you refresh your memory on for loops. The loop on the will run when i < listItems.lenght is true.

2 Answers

andren
andren
28,368 Points

The loop does not run infinitely, it only runs once for each li element that is present when the page loads. But I think I can guess where your confusion is likely stemming from as it's a pretty common misunderstanding when watching this video.

Is your interpretation of the loop that it is responsible for making the lis change case when hovered over? That is the impression a lot of people get, which does make it seem like the loop is running infinitely as the effect continues to work repeatedly.

In reality the for loop is not the one responsible for the case changing, the for loop is only responsible for attaching event listeners to the li elements. The same effect could have been achieved without using any loop at all, but then you would have to have manually attached the event listeners to each element, which would have lead to a lot of redundant code.

The way an event listener works is that you essentially tell the browser "Hey when x happens to this element run this code for me" where x is the event you are listening for.

So in this video two events listeners are attached to the lis one that runs when a mouse hovers over them and one that runs when a mouse stops hovering over them. The one responsible for monitoring the elements and running the code you wrote when one of those events occurs is the browser itself, not the loop.

If you are still confused or I misinterpreted what you where confused about, then just reply to this post and I'll do my best to clarify anything you want to know.