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

ian izaguirre
ian izaguirre
3,220 Points

Why Do I need an IF Statement?

I tried to create the program before seeing the video and I got it working but noticed that he had an IF statement and I never added any but my program works? His way seems more complicated and I wrote it so simple? Is their anything wrong as too why you would not write it my way?

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

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

do {
guess = parseInt( prompt('I picked a number between 1 and 10, guess what it is!') );
guessCount++;

} while ( guess !== randomNumber );




document.write('CORRECT! The Correct Guess was ' + guess);
document.write(' It took you ' + guessCount + ' trys to guess the correct answer!');

2 Answers

Steven Parker
Steven Parker
231,275 Points

The "if" statement is used in the video as part of a demonstration of creating a boolean status variable and using it to control the loop. This technique can be useful in more complex situations.

But given what this program actually does, your solution is more concise and works equally well. Good job. :+1:

ian izaguirre
ian izaguirre
3,220 Points

Oh I see, I was wondering if there was a problem with my code or if he was showing something additional for demonstration. Thank you for clearing that up.

NIck Hollenbeck
NIck Hollenbeck
5,601 Points

Thanks for posting this and for answering. I wrote the same solution and was wondering that same thing.