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

Why not try it this way?

I like the way Dave constructed his program in this video, but it seems that he added a few unnecessary variables (perhaps for instructional purposes). Wouldn't this way be the most efficient or am i lacking something that is needed as shown in Dave's program:

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("Guess a numberbetween 1 and 10.")); guessCount += 1; } while (guess !== randomNumber)

alert("It took you " + guessCount + " times to guess the number " + randomNumber + ".");

3 Answers

Steven Parker
Steven Parker
229,771 Points

:point_right:I suspect you are correct about "instructional purposes".

As the course examples get more complex, you will quite likely see opportunities for enhancement and optimization. In fact, in some courses the instructor actually invites you to further improve the example.

Your optimization here is a very good one, in that it shortens the code without making the functionality obscure (which is often a concern). Another opportunity for eliminating a temporary variable can be found in the *getRandomNumber^ function, which can be reduced to a single statement:

  return Math.floor(Math.random() * upper) + 1;

Noticing opportunities for improvements is a good sign that you're retaining what you've learned in other courses and lessons.

Thanks for the quick response and for pointing out that I didn't have to declare result of the function as a variable if it will only be returned. Much better.

Thanks!

John Silverstein
John Silverstein
6,290 Points

I imagine its better to use a flag variable for flexability. for example in a case where there are subsequent functions that are also influenced by the value in that flag variable - they behave according to a true or false value. there probably more reasons