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 trialGeorge Chatzispiros
2,912 PointsWill this script run smoothly?
I wrote the script with a slightly different way but i'm wondering if it's written in such a way that it might confuse the browser. Is it, by the way, necessary to use the "if" statement inside the "do-while" loop in order to run the script?
var randomNumber = getRandomNumber(10);
var guess;
var guessCount = 0;
function getRandomNumber( upper ) {
var num = Math.floor(Math.random() * upper) + 1;
return num;
}
do {
guess = prompt ("What is it?");
guessCount += 1;
} while (parseInt(guess) !== randomNumber)
document.write ("You tried " + guessCount + " times to guess number " + guess);
1 Answer
Steven Parker
231,275 PointsNo, you don't need an "if" statement when the condition to control the loop is coded directly in the "while" as you have done here.
The video demonstrates a technique using a boolean value to control the loop that is managed by the "if" statement. Your technique is actually more common, and I would even say preferable in cases like this where the condition is not very complicated.
Andrei Duhanes
14,155 PointsAndrei Duhanes
14,155 PointsHi,
The code works fine. You cant test it yourself. You need a condition to continue the loop and thus a condition to get out of the loop. If there is no while loop m after the first response the execution will end and it will go to the next line (document.write). If there is a while with no condition then it will never end. Thus you kinda need a condition to break out of the loop.