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
carlflynn
Courses Plus Student 2,198 PointsJavaScript Deep Dive Semantic Question
Hi There,
I'm working my way through the JavaScript Deep Dive, and just completed the section on Strings. During the lecture, Jim touched on how the use of quotation marks can mess up the string -- for example
var x='Jim's house is big';
The solution he mentions is
var x='Jim\'s house is big';
Is there a reason why one couldn't just use
var x='Jim's house is big' ? where the apostrophe is ' ;
Is it considered to be poor form to integrate HTML escape characters into JavaScript, or are both viable?
Only reason I ask is that I have most HTML special characters memorized, and may use them out of habit, as I progress through the Deep Dive. Want to make sure that I can break the habit early on, if it turns out to be a problem.
Thanks!
2 Answers
Matthew McCulloch
5,341 PointsIt depends on the situation, the thing to remember is that they are not equivalent strings.
For instance(from javascript console):
<code>
>var x='Jim\'s house is big';
undefined
>x;
"Jim's house is big"
>var y='Jim's house is big';
undefined
>y;
"Jim's house is big"
>x == y;
false
</code>
I would say you should stick with using the non html encoded string, now if you want to inject that string into an html element you have two choices. Either manually html encode it prior to injecting it, like you were suggesting or locate/create a premade js function to html encode the string as you are injecting it. My gut says handing it over to a function would be easier to maintain, however I honestly don't know of a premade script off the top of my head that would fit the bill.
JQuery has html encoding/decoding functions, but I'm not aware of how to use those with a javascript variable off the top of my head. It would be something interesting to look into though!
Edit: code display is giving me a hard time -_-
Adam Moore
15,825 PointsThat's a good question. I'm really not sure what js does with those characters. I imagine it will render them fine just as HTML does. Probably just easier to use and explain the other way.
carlflynn
Courses Plus Student 2,198 Pointscarlflynn
Courses Plus Student 2,198 PointsThank you for the response Matthew; I hadn't considered the two as being two separate strings, for validation purposes. You raise a really good point!
Code display gave me a pretty hard time too, haha.
Cheers!