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

B G
B G
1,866 Points

Can someone explain the + '</p>' in the: document.write('<p>Sorry, the number was ' + randomNumber + '</p>'); ?

I don't understand why he is adding the end of the paragraph like it's a separate string. I also don't under the ' before the </p>,

4 Answers

This document.write is displaying three things concatenated into one string, it has:

  • <p>Sorry, the number was
  • randomNumber
  • </p>

This is displayed all in one line because of the concatenation operator "+".

He has used this operator to include the opening string and closing tag because he is trying to display a variable mid way through the string (the randomNumber variable). If it had been included inside the quotation marks then it would just display the word randomNumber instead of it's value and so the closing tag has to be concatenated onto the end in it's own quotation marks .

B G
B G
1,866 Points

Why not use "" instead of HTML? "sorry, the number was".

He uses the ending paragraph tag because if you don't, all HTML elements after that opening paragraph tag will be seen in the browser as a part of that paragraph. Since the paragraph tag is not a self-closing tag, it has to have its closing tag.

https://developer.mozilla.org/en-US/docs/Web/HTML/Element/p

He didn't use just the quotes, although you can do it if you want, because he wanted to create an element (p in that case) to display the result in. You can display just text in an HTML document without any element encompassing it but it's better marking up all your content with elements for better accessibillity reasons. Also the browser might interpret it wrong in some occasions.

Rod R
Rod R
3,050 Points

He's slowing introducing students to HTML code. <p> </p> are opening/closing tags for a paragraph. You've also been seeing <h1>, <h1> which is for a leading header in HTML code (the line you want to be more prominent on a webpage). HTML and JS are generally different files but there can be some simple overlap, as Dave is doing in the videos.