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

What's the logic of this syntax for '8' to be printed at the end?

I did the exercises but I don't understand very well how is 8 printed in this case.

I have this Do While code:

i = Math.floor(Math.random() * 10);
do {
  text += i + ' ';
  i = Math.floor(Math.random() * 10);
  text += i;

} while (i !== 8)

And the While code:

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

Anyway, I don't trully understand how is exactly the number 8 being printed when we use text += i; at the very end of the conditions, because we're declaring the i variable as a random number at the beginning, right? Could someone explain to me please? Thank you in advance ! :)

2 Answers

Steven Parker
Steven Parker
231,269 Points

The "text += i" line adds the current randomly-chosen value to the end of the line. Only after that is done then the loop checks to see if that number was an "8". If so, it stops and the line can be printed (by code not shown here). Otherwise, the loop continues and more numbers are picked.

So since the loop is always checking to see if the last number added was "8", then you can be sure there will always be an "8" at the end of the line.

Now that second version picks one number before the loop starts, so there's a small chance (1 in 10) that the line will be totally empty because an "8" is picked first. But otherwise, it does the same as the first version.

So, the loop stores that number somehow, let's say, internally? That's how it's printed?

Edit: Yeah I was just playing with it, put 6 instead of 8 and the number 6 was printed at the end. The loop stores it I guess but it would be good to know why. Anyway, thank you very much for your answer!

Richard Verbraak
Richard Verbraak
7,739 Points

From top to bottom.

-- You declare a random number and store it in the i variable

-- If the var i does not equal 8 --> your while loop will run and keeps running until it is 8

-- It then adds that variable to the text variable --> print/log that out

Correct me if i'm wrong here, I don't know where your your text variable is declared or its contents are logged out.