Spanning javascript strings across multiple lines
I came across a weird feature of javascript last week, a way of spanning javascript strings over multiple lines.
To do it you put a ‘\’ character just before the line break and javascript knows it should keep going on the next line:
-
var mystring = "hello \
-
world";
I found it because I was trying to test something with a string that was coming over ajax split across multiple lines and I wanted to test a static string with the same space and tab characters in it.
I think this is quite handy if you want to create a big long bit of HTML. I find it a bit more readable than having lots of plus signs all through the code:
-
myElement.innerHTML = " \
-
<ul> \
-
<li>First item</li> \
-
<li>Second item</li> \
-
<li>Third item</li> \
-
</ul>";
The javascript line continuation character doesn’t put a line break in the string. You still need to explicitly put in a \n character if you want a line break in the string.
Not part of official javascript standard
It’s not part of the EMCAScript standard. It’s something the browsers support for backwards compatibility. I guess that means it’s possible it could one day be deprecated. That’s a bit of a pity because I think it’s quite useful for making string concat easier to read.

June 26th, 2007 at 11:54 am
Javascript, as many other languages such as Java, C#, PHP, Actionscript, C++, Objective-C, etc, borrowed much of its syntax from the C language (if you don’t believe me, just google for source code or a tutorial on C). Having said that, this is a feature originally found in C, so it’s safe to assume that Javascript inherited it from it as well.
- Armando (”Rafael”) Wall.
June 16th, 2008 at 1:07 am
It’s a different solution:
Using a line break with the escape character, you just create a string literal, though it’s defined in two lines of code.
Using + you are creating two string objects and concatenating them to create a third string object. That takes more time and memory. It may seem it’s not so bad, but if you do that many times with a not too powerful architecture (i.e. java ME), you will end up slowing your application because memory allocation and garbage collection will be quite more requent.