Splitting a long JavaScript String across multiple lines

Whilst reading a comment by Mike DeBoer on Ajaxian about delimiting JavaScript strings with backslashes, I thought it’s worth mentioning it here as well, if only to remind myself.

String concatenation always creates a new string.

Thus, writing:

 
var str = "This is a long" +
  " string. That's why we want to " +
  " split it over several lines";
 

is slower & more memory intensive than writing:

 
var str = "This is a long\
 string. That's why we want to\
 split it over several lines";
 

Just be careful you don’t have trailing spaces as that will mess it up.

Tags: ,

3 Responses to “Splitting a long JavaScript String across multiple lines”

  1. Nic Wise says:

    So, whats the result from the second one? I woudl expect:

    var str = “This is a long string. That’s why we want to split it over several lines”;

    which isn’t whats desired, right?

    the slower and more memory intensive part, however, would be measured in bytes (10’s of) and maybe milliseconds – hardly enough to mess up your code’s readability for…!?

  2. Nic Wise says:

    oops, formatting messed that up. Was ment to be:

    var str = “This is a long(8 spaces)string. That’s why we want to(8 spaces)split it over several lines”;

  3. elduderino78 says:

    You are absolutely right. I fixed the example!

    As always: this doesn’t make an awful lot of difference with 1 example but across a page with numerous scripts & other things, it should be avoided, like for … in loops, etc. Don’t forget: we don’t all use Chrome, Firefox 3 & Safari 3.

    Thanks for making me aware of it!

Leave a Reply