littlewolf littlewolf - 1 year ago 65
Javascript Question

What's the difference between line breaks in template literals and '\' in string literals?

I was reading about template literals in the ES2015 spec which allows you to create (among other things) line breaks like so:

var brokenStr = `This is
a broken
string.`; //This is a broken string

We can also break a string literal with the backslash

var anotherBrokenStr = 'This is \
also a broken \
string.'; //This is also a broken string.

Is there a performance difference between the two? Which is considered best practice?

I have looked at the the documentation here as well as searched SO.


When I output as follows, I get a single line.

document.getElementById('logger').innerHTML = brokenStr;

When I use
I get this in Chrome inspector:

This is also a broken string.

Which colapses the whitespace to a single space in the browser/

Update: Update:

It appears that the template literal includes a
character. Then, is there any difference between the first example and this, or is it just syntax sugar?

var anotherBrokenStr = 'This is \\n
also a broken \\n

Answer Source

Here's the output of my Node.js REPL showing the difference between the two:

> `hello
... world`
> 'hello\
... world'

In the first case we get a newline between 'hello' and 'world'. In the second case we don't.

Edit: Dear Lord, you're thoroughly confused.

HTML doesn't

respect newlines.

It doesn't matter how many newlines

you put in between your lines.

HTML will still print it

as a single line.

Hope that makes things clear.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download