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

I am confused why do we need a conditional statement (IF) inside do-while loop

Hi,

I understand the logic behind this loop, but I don't quite yet understand what are the benefits of checking with the conditional statement if the answer is correct, and then use another condition to break the loop? Don't we have the same result if we would run the code like this:

var randomNumber = getRandomNumber(10); var guess; var guessCount = 0;

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

do { var guess = prompt(" Guess a number between 1 and 10 "); guessCount +=1; } while (parseInt(guess) !== randomNumber )

document.write(" Your guess is correct.The random number was " + randomNumber + " and it took you " + guessCount + " guesses!");

Maybe you could provide the original code/challenge? It is not linked.

1 Answer

Steven Parker
Steven Parker
243,344 Points

The code sample in the lesson is probably intended to illustrate some common coding practices, and may not be the most efficient approach to the specific task and situation.

I would agree that your solution is both more concise and efficient than the sample. Good job! :+1: