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 trialSean Flanagan
33,235 PointsJavaScript won't work
Hi. My program won't work. Does anyone know why? Here's the JS:
var correctGuess = false;
var randomNumber = Math.floor(Math.random() * 6 ) + 1;
var guess = prompt('I am thinking of a number between 1 and 6. What is it?');
if (parseInt(guess) === randomNumber ) {
correctGuess = true;
}
if ( correctGuess ) {
document.write('<p>You guessed the number!</p>');
} else {
document.write('<p>Sorry. The number was ' + randomNumber + '.</p>');
}
It doesn't prompt an answer. Thanks for any help offered.
Sean
2 Answers
Iain Diamond
29,379 PointsHi Sean,
Your JavaScript works perfectly fine in a browser. How are you running it?
I tested it by writing the following to a test.html file and opening it up in a browser:
<script>
var correctGuess = false;
var randomNumber = Math.floor(Math.random() * 6 ) + 1;
document.write('<p>The number is ' + randomNumber + '.</p>');
var guess = prompt('I am thinking of a number between 1 and 6. What is it?');
if (parseInt(guess) === randomNumber ) {
correctGuess = true;
}
if ( correctGuess ) {
document.write('<p>You guessed the number!</p>');
} else {
document.write('<p>Sorry. The number was ' + randomNumber + '.</p>');
}
</script>
Sean Flanagan
33,235 PointsHi Iain.
I've run it again and now it's working fine. Strange, but at least it's sorted.
Thanks and apologies
Sean