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 trialMichael Mersiades
12,920 PointsWhy 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.
2 Answers
andren
28,558 PointsThe 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 li
s 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 li
s 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.
Moinul Haq
Front End Web Development Techdegree Student 11,178 PointsSomething wrong with your exit condition. Cross check it.
Antti Lylander
9,686 PointsAntti Lylander
9,686 PointsI recommend you refresh your memory on for loops. The loop on the will run when
i < listItems.lenght
is true.