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 The Solution

Nour El-din El-helw
Nour El-din El-helw
8,241 Points

Loop 5 Killed

The fifth loop in the "doWhileLoops.js" and "whileLoops.js" get killed when i try to run the program but what is killing a loop and why is it happening? Here is a snapshot of my workspace http://w.trhou.se/t4age43ih1 .

1 Answer

andren
andren
28,558 Points

Due to an error in the code of the loops they will run infinitely. Since infinite loops consume a large amount of resources and are rarely intentional, Treehouse automatically kill loops that appear to be running infinitely.

The reason the loops end up running infinitely is due to this line:

i = Math.floor(Math.random * 10);

Which is present in both of the loops. You have forgotten to place parenthesis () after your call to the Math.random method. The parenthesis is what tells JavaScript to actually call the method, without those it will instead place a reference to the method itself there. Since a method definition cannot be multiplied the result of Math.random * 10 is NaN (Not a Number).

Since NaN is not equal to 8 (and i is always set to NaN) the while condition of the loop i !== 8 will always remain true. If you fix the code like this:

// Do while loop
do {
  i = Math.floor(Math.random() * 10);
  text += i + ' ';
} while ( i !== 8 ) 

// While loop
i = Math.floor(Math.random() * 10);
while ( i !== 8 ) {
  text += i + ' ';
  i = Math.floor(Math.random() * 10);
}

Then your loops will work.

Nour El-din El-helw
Nour El-din El-helw
8,241 Points

Oh! Thanks. I really hate those kinds of bugs

Aleksejs Sitdikovs
Aleksejs Sitdikovs
4,076 Points

On the last one " While loop" at the bottom after While loop need to add
text += i + ' ';

or it will never print 8 as the last number, it will exit the loop without showing that number.