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 The Solution

Keytron Brown
Keytron Brown
15,828 Points

Back slash

Can I have a better explanation of this backslash thing in your last step solution please?

1 Answer

Jonathan Grieve
MOD
Jonathan Grieve
Treehouse Moderator 91,253 Points

I'll try. :-)

When you put something inside a string, which in lamens terms is text inside single (') or double (") quotes.... JavaScript recognises that as a string character, and only a string character. If for example, you wanted to put a number inside a string and use that to make a calculation you couldn't do that because a number is recognised as a string of text.

To help out with this you can use what are called "escape" characters where you can make characters behave differently from strings.

To illustrate, let's use the example in the workshop.

alert("The string \"" + completeName + "\" is " + characterCount + " charactersLong.");

It looks a bit messy but basically what is happening is the values of variables are being superimposed into one long string

If you were to run this code it would display something like...

The string "completeName" is " 10 charactersLong.

And the reason we can use "" inside a string of double quotes is because we are using the backslash escape character to let JavaScript know we want to use quotes in a string.

So "\" tells the string to treat the next character as a string regardless.

There are other ways to get around this.

For example, we can say alert("A string with 'single quotes' instead of double quotes"), and JavaScript will recognise that. Or you can use template literals. But that comes a little bit later on.

But if you're using a simple string the backslash is the way you can add double quotes into a double-quote string without breaking your code.

Keytron Brown
Keytron Brown
15,828 Points

Ok thank you very much. This works for me.