Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript JavaScript and the DOM (Retiring) 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
229,657 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.