JavaScript JavaScript Loops, Arrays and Objects Simplify Repetitive Tasks with Loops A Closer Look at Loop Conditions

Alex Lang
Alex Lang
1,110 Points

Why won't this work?

var upper = 10000;
var randomNumber = getRandomNumber(upper);
var guess;
var attempts = 0;


function getRandomNumber (upper) {
  return Math.floor(Math.random() * upper ) + 1;
}

while (guess !== randomNumber ) {
guess = getRandomNumber( upper );
attempts += 1;  
}
document.write("<p>The random number was " + randomNumber + "</p>");
document.write("<p>It took the computer " + attempts + "attempts to get it right.</p>");
KRIS NIKOLAISEN
KRIS NIKOLAISEN
Pro Student 49,702 Points

It seems like it works to me. What does it not do?

Alex Lang
Alex Lang
1,110 Points

When I preview it, nothing pops up.

5 Answers

KRIS NIKOLAISEN
PRO
KRIS NIKOLAISEN
Pro Student 49,702 Points

The source for your script is app.js. But the code is in while.js. Make the following change in index.html

<script src="while.js"></script>
Alex Lang
Alex Lang
1,110 Points

When I preview it, nothing pops up.

Steven Parker
Steven Parker
173,644 Points

Are you using the workspaces? If so, you could make a snapshot of your workspace and post the link to it here. Then we could replicate your issue.

I'm having the same problem and i added the script anyone know what's wrong?

Steven Parker
Steven Parker
173,644 Points

If the answer here didn't resolve your issue you may have a different cause. Start a fresh question where you can share your own code and we can take a look. Remember to use Markdown formatting.

I tried EVERYTHING....still does not WORK! So frustrated!

Steven Parker
Steven Parker
173,644 Points

Start a fresh question where you can show your own code, I'll bet someone can help!

Steven Parker
Steven Parker
173,644 Points

This code does work, but remember when dealing with random numbers, the specific results you get will vary from those in the video. In fact, if you try it more than once, you will notice that the number of attempts will be different each time.

Steven Parker
Steven Parker
173,644 Points

Looks like Kris beat me to it, but you can see that snapshot made the answer possible.

Steven Parker
Steven Parker
173,644 Points

Would the person who downvoted this answer please leave a comment and let me know what I could do to improve it? Thanks!