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

Eetu Hämäläinen
Eetu Hämäläinen
1,479 Points

Improvement to the code.

Hello, I'm trying to think a correct way to how to prompt and ask the number from user and then the computer will guess it.

//This code is working but the prompt value is only the upper value.

var upper = prompt('Write a number between 1 to 10000.'); var comprandomNumber = getRandomNumber(upper); var guess; var attempts = 0;

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

while ( guess !== comprandomNumber ) { guess = getRandomNumber( upper ); attempts = attempts + 1; } document.write('<p>The random number was: ' + comprandomNumber + '<p>'); document.write('It took the computer ' + attempts + ' attempts to get it right.');

//I tried to make var comprandomNumber = upper; but I guess thats not right way.

2 Answers

Steven Parker
Steven Parker
173,991 Points

If you want the computer to guess your number, you won't need to select a random one to start with. But you will need to convert the string input from "prompt" into a number if you want to use a type-sensitive comparison ("!=="):

var upper = 10000;
var comprandomNumber = parseInt(prompt("Write a number between 1 to 10000."));