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 A Closer Look at Loop Conditions

Is my version correct?

Tried to solve it before watching the instructor's solution, this is what I got: Is it as good, or almost as good, or should I crawl into a hole and be ashamed?

var totry = getRandomNumber(10000); var Computerguess = getRandomNumber(10000); var guessCount = 1;

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

while (totry !== Computerguess) { var Computerguess = getRandomNumber(10000); guessCount+=1; }

document.write("The random number was " + totry + ", and it took the computer this many tries:" + guessCount);

Hi I just make your code more readable:

var totry = getRandomNumber(10000);
var Computerguess = getRandomNumber(10000); 
var guessCount = 1;

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

while (totry !== Computerguess) { 
    var Computerguess = getRandomNumber(10000); 
    guessCount+=1; 
}

document.write("The random number was " + totry +
 ", and it took the computer this many tries:" + guessCount);

2 Answers

Pesonally I don't like the order of your code. IMO the function should be at the beginning since javascript reads "from the top to the bottom" (yes yes thats no problem for functions :D), but that is just personal preference (also it makes your code better readable...since the user will know what getRandomNumber is doing and doesnt have to search the function first. And when you work with other people...and with much bigger files ... legibility is a big part of good coding/workflow).

But in functionality your code is perfectly fine and will work

Hey Tobias, thanks for posting my code in a more readable way, I was a bit too lazy for that at 6am ;) I kept the vars at the beginning, because the instructor does it the same way - but thanks for the advice. I suppose, it does make a difference in bigger files, so I'll make it my new habit to put fuctions first while I'm still learning. Glad to hear it'll run though.

https://jsbin.com try this to run your code it really helps you.