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

FEEDBACK on BONUS CHALLENGE.

// 5. BONUS CHALLENGE: Write a while loop that builds a string of random integers
// between 0 and 9. Stop building the string when the number 8 comes up.
// Be sure that 8 does print as the last character. The resulting string 
// will be a random length.

print('5th Loop:');
text = '';
// Write 5th loop here:

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

while(i <= 9) {
  i++;

  if(i === 8) {
    text += text.concat(i);
    break;
  } else if(i > 8){

    break;
  }

  text += i + ' ';
}

print(text); // Should print something like `4 7 2 9 8 `, or `9 0 8 ` or `8 `.

1 Answer

Steven Parker
Steven Parker
229,732 Points

Good start, and the code runs without errors, but you have a few issues yet:

  • the "print" function is called but not defined here
  • the code picks only one random number instead of a random number for each digit
  • if the random number picked is 8 or 9, no numbers will be shown at all
  • if the random number picked is less than 8, the numbers shown will be in sequence up to 8
  • the sequence up to 7 will be repeated twice
  • the output will never include "0"

I'll bet you can take care of all these in your next revision. Happy coding!

As always thanks. I was able to fix it:

let text = '';

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

do {

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

text += i + ' ';

} while(i != 8)



console.log(text);
Steven Parker
Steven Parker
229,732 Points

Excellent! Concise and efficient!

Two minor suggestions:

  • declare but don't assign "i" outside of the loop (just "let i;")
  • indent the lines inside the loop body for readability

But really good job! :+1: