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

BONUS CHALLENGE in forLoops.js. Is it possible to get the exact same solution?

I tried the Bonus challenge with for loop, but the ending 8 wasn't in the string. Is it possible to get the same solution like with while and do..while loops? I tried with this :

for (let i = Math.floor(Math.random() *10); i !==8 ; i = Math.floor(Math.random() *10)) { text += i + ' '; }

3 Answers

Steven Parker
Steven Parker
229,785 Points

Since the value 8 is the limit condition, it will not be added inside the loop. This is the same thing that occurs in the video example that uses "while". So you need an extra statement to add it after the loop, just as is done in the video example. But with the code above, the variable "i" is not accessible from outside the loop, so you can substitute a literal instead:

text += "8";

Another way would be to build the string as part of the loop increment clause. Then the loop body could be left empty:

for (let i; i !== 8; i = Math.floor(Math.random() * 10), text += i + " ");

Thank you Steven, it was really helpful!

Lucas Guimarães
seal-mask
.a{fill-rule:evenodd;}techdegree
Lucas Guimarães
Front End Web Development Techdegree Student 3,900 Points

That is one alternative solution as well. Numbers between 0 till 9 and stopping and showing in 8.

for (s = 0; s != 8 ;) { s = Math.floor(Math.random() * 9); text += s + ' '; }

Steven Parker
Steven Parker
229,785 Points

This won't give you the correct number range — if you multiply random by 9 and round down, the largest value you can get is 8 Also, you should declare the loop variable with "let" or "var", but it's not necessary to initialize it.