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
brandonlind2
7,823 PointsCan someone explain to me why this loop isnt working?
function randomNumber(top,lower){return Math.floor(Math.random() * (top - lower) + lower) + 1; randomNumber(100,10) var correctGuess= false;}
var attempts=0;
var random= randomNumber(100, 10);
while(correctGuess===false){var guess= randomNumber(100, 10);
if(guess===random){correctGuess===true;}
attempts+=1;}
1 Answer
elk6
22,916 PointsHi Brandon,
Multiple things. Your closing brackets are off. Half of what you wrote is inside the function body. Since you have a return statement right at the start, the rest will not get executed. And even if it would it would not work.
Also, you have written this:
if(guess===random){correctGuess===true;}
This will not make correctGuess true but just checks if correctGuess equals true, since that is never the case ( it doesn't get changed after all ) you will get stuck in an endless loop.
So, try it like this, this might be what you are looking for:
function randomNumber(top,lower){
return Math.floor(Math.random() * (top - lower) + lower) + 1;
}
randomNumber(100,10)
var correctGuess= false;
var attempts=0;
var random= randomNumber(100, 10);
while(correctGuess===false){
var guess= randomNumber(100, 10);
if(guess===random){
correctGuess=true;}
attempts+=1;
}
Also, might be because of copy/paste but try to keep your indentation like it should, this will make your code a lot more readable.
Elian