Last Updated: September 09, 2019
· seattledanny

Do / While Loop - Java Script

Our first project at Code Fellows was to create a questionnaire game that would run in a loop until the user answers the question correctly. There are few different ways to accomplish this task, but the one that I chose was a do / while loop.

A do / while loop basically tells the computer to execute code in a loop, until certain conditions are met. For my game, i asked the question "How much wealth do the top 10 richest people on the forbes list have? in billions of dollars." The answer to this is 526 billion. I set it up so that if the users guess was below, it would say you are guessing to low and you are off by X. If the guess was too high, the same thing - you are too high, you are off by X.

I have that inside of a do / while loop, that basically says, while their guess (howMuch), is not equal to, the answer (answer), then keep running the loop. Once they guess correctly (howMuch = answer), then end the loop.

Here is the code below, it was a fun project that took a while to figure out where to put the do / while loop.

'code' - javscript

 <script type="text/javascript">
 var forbes1 = function(question1) {
do {
var answer, howMuch, difference; 
    answer = 526
    howMuch = prompt( "How much money is on the Forbes list of the top 10 wealthiest people in the world? (in billions)") 
    difference = howMuch - answer;
if (howMuch == answer) 
    document.write("GREAT JOB!!!!!!")
    return ("you are right!")   

else if (howMuch > answer)
    document.write("your guess was too high, you were off by " + difference + '\n')

else if (howMuch < answer)
    document.write("your guess was too low, you were off by " + difference + '\n')
} while (howMuch != answer);

1 Response
Add your response

In this case, do-while loop is more semantically opt, because it executes the loop content for one time and then check for loop breaking conditions. of course, same thing can be done by a while loop also, but do-while is much more readable.

over 1 year ago ·