0

Is it just:

var str = 'Hello';
str += ' World';

?

In most languages you can do this, yet some frown upon it. And in most of those languages they have a stringbuilder which more efficient, faster, and less prone to memory-leaks. So I was wondering if Javascript had something similar or just "better" way of appending strings to each other.

dotnetN00b
  • 5,021
  • 13
  • 62
  • 95

4 Answers4

0

You can go for concat. You can append one or more strings with this function.

var str = 'Hello';
str = str.concat("world")

But I am not sure about reasons like performance.

Mritunjay
  • 25,338
  • 7
  • 55
  • 68
0

Yes, this is the way you do it in JS.

var str1 = 'Hello';
var str2 = 'World';
console.log(str1 + ' ' + str2);

or you can still create your own string formatting function.

Community
  • 1
  • 1
Nick Rameau
  • 1,258
  • 14
  • 23
0

According to jsperf, the 'fastest' way to do it is simple concatenation with the '+=' operator, as such:

'str1' += 'str2'

It does vary browser to browser. Also note that the alternative methods (concat, + operator, etc) aren't very much slower. At this point, you should focus on readability.

slaughterize
  • 714
  • 1
  • 7
  • 11
0

There are some ways to concatenate strings in Javascript:

  • The addition operator (+);
  • The assigment operator (+=);
  • The concat method;
  • The string array addition;

The fastest one, according to this, is the simple addition or assignment operator. If you are concatenating only a few strings, the performance discrepancy will go unnoticed no matter which browser is being used. When doing this operation many times, it will cause some slowdowns on some browsers.

Press the button "Run tests" in the above link.

chiapa
  • 4,362
  • 11
  • 66
  • 106