JavaScript JavaScript Basics (Retired) Making Decisions with Conditional Statements Build a Random Number Guessing Game

Patience Anaya
PRO
Patience Anaya
Pro Student 2,400 Points

document.write vs alert for the response.

I cant seem to get my code to run when I use document.write, though it works fine when I use alert. Does anyone have any tips or reasons why that might be. Here is the code with document.write.

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) {document.write ('<p>You guessed the number</p>') 
} else { 
  document.write ('<p> Sorry the number was ' + randomNumber +</p>')
}
Steven Parker
Steven Parker
182,492 Points

And this illustrates an advantage of formatting, the syntax coloring gives you a clue to the problem!

1 Answer

Steven Parker
Steven Parker
182,492 Points

The function should work fine once you fix the missing quote mark:

//document.write ('<p> Sorry the number was ' + randomNumber +</p>')       <-- original
  document.write ('<p> Sorry the number was ' + randomNumber + '</p>')  // <-- fixed
devina christabela
devina christabela
12,525 Points

The template literal easier to apply for me, so

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) {
    //template literal using backtick sign
    document.write (`<p>You guessed the number</p>`)
} else { 
    document.write (`<p> Sorry the number was ${randomNumber}</p>`) 
}
Steven Parker
Steven Parker
182,492 Points

Template literals are great, but I don't think they have been introduced yet at this point in the course(s).