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

Why does the console repeat loop: 5 over and over again at 2:51 in the video https://teamtreehouse.com/library/let-and-c

Hey guys,

I need some clarification help plz.

I can't understand why when we set i = 3 in the doLoop function and then have the for loop run, the output is an infinite series of loop = 5 ' s.

This is at 2: 51 , in the video at :

https://teamtreehouse.com/library/let-and-const

Thanks in advance,

Sam

1 Answer

andren
andren
28,558 Points

The loop ends up running indefinitively due to the ending condition never being reached. The condition for running the loop is that i is less than 10.

The for loop is setup to automatically increment i once each run so normally it will only run 10 times, but if you actually set i to 3 within the loop then then though it is increment by one each run it will always be less than 10 since it is reset to 3 in each run.

Basically i normally starts at 0 and increments by one until it reaches 9, with the code change it starts at 0, then gets set to 3, and then continues to be set to 3 each time the loop runs, never reaching 9.

The reason why 5 is the number printed out is that i is set to 3, then it is increment by the loop automatically, then when it is passed to the doLoop function it has 1 added to it.

Edit: Some minor corrections.