Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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
210,850 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."));