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 Create the Loop – One Solution

Kelsey Donegan
Kelsey Donegan
3,342 Points

How would I change the value of randomNumber each time?

I've been trying to make it so that each time the number was incorrectly guessed, it would also change. Mostly just to have a better understanding of the code and how it works. Unfortunately I can't figure it out and I'm hoping someone here can tell me. Thanks!

1 Answer

Brenda Butler
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Brenda Butler
Front End Web Development Techdegree Graduate 18,839 Points

Hi Kelsey! This is what I did to change the randomNumber each time (and I wrote it to the screen just so I knew the random number before I guessed so I could test for what happens when the number is guessed correctly). I also set i<=50 since the loop could really go on infinitely if the person never guesses correctly! I also deleted the const randomNumber declaration at the top of the document since we want to be able to change it for each loop iteration.

for (i=0; i<=50; i++) {
  let randomNumber = getRandomNumber(10);
  document.write(randomNumber);
  guess = prompt('Guess a random number between 1 and 10');
  if (randomNumber == guess) {
    main.innerHTML = '<p> You guessed the number!</p>';
    break;
  } 
}