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

I don't understand how that for loop is working.

Assume that i=0 and my mouse is on the first item (and never goes elsewhere). That means the first item is transformed to uppercase now and the computer checks the second piece of code inside the for loop (i still equals 0) and since we assumed the mouse didn't move, the item should stay uppercase.

If we don't move the mouse while going through the for loop, all items in the list should stay lowercase and the computer should exit the loop when i equals the number of items. That means that now, if we hover the mouse over the list items it shouldn't happen anything since the loop ended (and the first item should remain uppercase).

However, the behavior of the list items after running the code in the video is completely different from what I expected.

I am so confused about how the computer executes the code. I hope I make sense.

Thank you!

1 Answer

Steven Parker
Steven Parker
206,355 Points

The "for" loop establishes event listeners to monitor the mouse. The code inside them that changes the case is not executed by the running of the loop.

But once the listeners are set up, that code runs every time the mouse is moved.

Thank you, sir! Now I understand.