1

I heard at someplace that I can't remember right now, than it was a smart idea to shorten longer strings into shorter substrings. Should I do this? What are the pros, and cons?

Sample:

var str = "some extremly long string for the sample I am making for this Stack Overflow question. Must add more words to make longer.";
alert(str);

or

var str1 = "some extremely long string";
var str2 = "for the sample I am making";
var str3 = "for this Stack Overflow question.";
var str4 = "Must add more words to make longer.";
alert(str1 +str2 +str3 +str4);
Travis
  • 1,274
  • 1
  • 16
  • 33

3 Answers3

3

Your two versions are not equivalent, since the concatenated version is missing spaces.

If you do want to break up strings, it's often considered good practice to join them:

var str = [
    "some extremely long string",
    "for the sample I am making",
    "for this Stack Overflow question.",
    "Must add more words to make longer."
 ].join(" ");

I see this pattern quite a bit and it is indeed more readable IMO.

As ES6 gains traction, more people may start to use the mulit-line capability offered by template strings:

var str = `some extremely long string 
for the sample I am making 
for this Stack Overflow question. 
Must add more words to make longer.`;
0

The only reason to do this that I can think of is readability. Having one very long line in your source code is just not very readable. This is neatly illustrated by your question: one has to rely on horizontal scrolling to read the string in the first example; the second example has no such problem.

For a discussion of how to split a long string literal in JavaScript, see this answer to another question.

Community
  • 1
  • 1
NPE
  • 486,780
  • 108
  • 951
  • 1,012
0

I am not aware of any such optimization. If it is a matter of readability you can use backslash to write a multi-line string literal:

var string = "some extremely long string\
 for the sample I am making\
 for this Stack Overflow question.\
 Must add more words to make longer.";
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928