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 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.