Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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
218,692 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.