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

Michael Helgesen
Michael Helgesen
1,140 Points

Browser crashes

Hi everyone! I've just started out learning JavaScript and I'm having a blast so far. But in this case my browser crashes when running this script. I get the prompt, but the number never gets the same as the random number, and the browser freezes. I've looked over this code so many times now, but cant seem to find anything wrong. Have I maybe just gotten to tired to find it?

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

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

do { guess = prompt("Velg nummer mellom 1 til 10"); guessCount += 1; if (parseInt(guess) === randomNumber) { correctGuess = true; } } while ( ! correctGuess ) document.write("du gjettet riktig"); document.write("Det tok deg " + guessCount + " forsΓΈk Γ₯ gjette deg frem til " + randomNumber);

Michael Helgesen
Michael Helgesen
1,140 Points

Ok. My bad. I just kept typing the same number! I thought the browser chose a new number each time I chose wrong. If that was the case I guess the javascript would have to restart each time you chose wrong.

1 Answer

Steven Parker
Steven Parker
229,744 Points

You could write it that way if you want.

You could certainly change your code to pick a new number after each guess, but that would mean you would not learn anything from missing, So then every guess would only have a 10% chance of being right. It might take very many guesses before you got one.

Michael Helgesen
Michael Helgesen
1,140 Points

Hi Steven! That`s right, and that does not sound fun :) It was much more fun in one of the earlier classes with the JavaScript that alerted if you needed to go higher or lower to guess right. A 10% chance just sounds tedious. JavaScript is fun anyway tho!