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

Stacey Auguste
seal-mask
.a{fill-rule:evenodd;}techdegree
Stacey Auguste
Full Stack JavaScript Techdegree Student 1,566 Points

Solved the whileLoops bonus question in a different way. Is this still considered good code?

I solved the challenged using the code below. It doesn't have the declaration of the i variable before the while loop and it waits to modify the text string until after running the Math methods so the number 8 prints to the console.

It works but I'd like to make sure it's considered good code.

My solution:

while (i !==8) { i = Math.floor(Math.random() * 10); text += i + " "; }

Instructors solution:

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

while (i !==8) { text += i + " "; i = Math.floor(Math.random() * 10); } text += i;

Thanks in advance!

1 Answer

Steven Parker
Steven Parker
229,921 Points

Well, you'll wind up with an extra space at the end of "text". But more importantly, when you first enter the loop you'll be testing "i" before any value has been assigned. You may get away with it, but "good practice" is to never assume what a variable might contain unless your code put something into it.

The "do/while" loop form would be better suited to your modifications, since it allows the body code to run before the first test is done.