Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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

Micole Noddle
Micole Noddle
5,797 Points

Why are we using document.write instead of alert in this code?

In the lessons, we use document.write in our conditionals, but in the challenges, we use alerts. Can we use an alert in this code instead of document.write? Why or why not? What are the benefits to using document.write instead of alert (and vice versa)? Oh, also, I've seen several people advising to avoid document.write anyway because it's obsolete. Is this true? Here's the code from this lesson:

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>"); 
}

2 Answers

chris slaats
chris slaats
5,996 Points

alert is used to create a pop-up box which displays information. While document.write is used to add the information to the page itself and make a more permanent change rather then just a pop-up text box the user can just exit out of. In the end as far as my knowledge goes it just depends on how you would like to relay the information back to the user. whether that be another pop-up box or change the contents of the webpage itself depending on the user input. As for document.write being obsolete i wouldn't have a clue but it seems like a pretty useful tool as far as i can tell.

Thanks Chris, I think is a good answer.