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 JavaScript Loops, Arrays and Objects Simplify Repetitive Tasks with Loops A Closer Look at Loop Conditions

Trying to modify the code - is it an endless loop?

Hi everyone,

I would like to ask your for asistance with the code below. I have modified it a bit to have a user input instead of computer vs. computer guessing the random number, but it seems that I made a mistake somewhere as I cannot get the loop end. Could you please help?

var randomNo = randomNumber(); var guess = guessNumber() var attempts = 0;

function randomNumber() {

var numberGenerated = Math.floor( Math.random() * 6 ) + 1;
return numberGenerated

}

function guessNumber() {

var question = parseInt(prompt("Gusss a random number from 1 to 6 generated by the application."));
return question

}

while( guess !== randomNo )

{ guessNumber() attempts += 1; }

document.write("The random number was " + randomNo + "." ); document.write("The number of attempts was " + attempts + ".");

Thank you,

Ewa

1 Answer

Joel Bardsley
Joel Bardsley
31,249 Points

Hi Ewa,

You've assigned the guess variable at the start but you're not updating its value each time the guessNumber() function is executed, causing the infinite while loop. To fix this, you could update the guessNumber() function as follows:

function guessNumber() {
// Replace the newly created 'question' variable with the existing guess variable
guess = parseInt(prompt("Gusss a random number from 1 to 6 generated by the application."));

// Return the updated value of guess based on the user's input:
return guess;

}

Hope that helps.

Thank you Joel! That was really helpful :-)