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 `do ... while` Loops

Chris Carr
seal-mask
.a{fill-rule:evenodd;}techdegree
Chris Carr
Front End Web Development Techdegree Student 12,900 Points

Do While Loop Alternative Code

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 ("Guess a number from 1 to 10");
 guess = parseInt(guess);
 guessCount += 1 ; 
} while (guess !== randomNumber);

document.write("<p>You guessed correctly! " + randomNumber + " is the correct number.</p>");
document.write("<p>You guessed " + guessCount + " number of times.</p>");

Does my code do the job? Or will I need a conditional statement like in the video?

2 Answers

Stephan Olsen
Stephan Olsen
6,650 Points

Your code does the job and is perfectly valid. When coding, there are various ways to complete the task you're doing. How you write the code comes down to preference.

Devjyoti Ghosh
Devjyoti Ghosh
2,422 Points

Why is there a semicolon after the do while loop? Shouldn't it give a syntax error?

Chris Carr
seal-mask
.a{fill-rule:evenodd;}techdegree
Chris Carr
Front End Web Development Techdegree Student 12,900 Points

It is the correct syntax. The semi colon comes after the closing parentheses in the while condition. The do while loop is different other loops as it is the only one that requires a semi colon. Someone correct me if I'm wrong.

Devjyoti Ghosh
Devjyoti Ghosh
2,422 Points

From what I could find online in Javascript semicolon after do while seems to be a styling choice and is optional. In other languages like c++ and java it is required. Source