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

Sean Keane
Sean Keane
1,678 Points

Semantics on the else statement.. ' vs. "

//For the else statement, I had:

document.write('<p>Sorry, you're wrong. The number was ' + randomNumber + '</p>');

//This is exactly as shown in the video. And in the js console, it said line 6 had a missing closing parenthesis. I changed it to:

document.write("<p>Sorry, you're wrong. The number was " + randomNumber + "</p>");

//It worked fine after changing the single quotes to double quotes.. Why?

2 Answers

andren
andren
28,524 Points

Because your string contains the word you're. That word contains a single quote (technically an apostrophe, but they use the same symbol) which means that as far as JavaScript is concerned your first string looked like this: '<p>Sorry, you' and then the rest of the text was considered to be outside of the string, which caused JavaScript to crash since that text does not form a valid command.

Switching to double quotes fixed the issue since the apostrophe within the string no longer closed the string early. This issue did not occur in the video because the message the instructor wrote did not contain "you're" or any other word containing an apostrophe.

You could have fixed this issue by using an "escape character" which is a special character that tells JavaScript that it should treat the next character as literal text and not assign it any special meaning. In JavaScript (and most other languages) the escape character is the backslash "\" symbol.

So if you changed your code to this:

document.write('<p>Sorry, you\'re wrong. The number was ' + randomNumber + '</p>');

It would also have worked properly. It's worth noting that the same type of issue occurs if you use double quotes to start a string that contains double quotes within it.

Sean Keane
Sean Keane
1,678 Points

OMG. I can't believe I didn't catch that after so many times. I'm familiar with escape characters but I really do appreciate the response. Wow! >_>