Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

String concatenation in JavaScript

DZone's Guide to

String concatenation in JavaScript

· Web Dev Zone ·
Free Resource

Deploying code to production can be filled with uncertainty. Reduce the risks, and deploy earlier and more often. Download this free guide to learn more. Brought to you in partnership with Rollbar.

There are two ways of doing string concatenation in JavaScript. This post demonstrates them and explains which one is faster.

1. + operator. The + operator does string concatenation as soon as one of its operands is a string. Then the other operand is converted to string. Example:

    > "Say hello " + 7 + " times fast!"
    ’Say hello 7 times fast!’
Alternatively, you can use += where
    a += b
is an abbreviation for
    a = a + b
Example:
    > var str = "";
    > str += "Say hello ";
    ’Say hello ’
    > str += 7;
    ’Say hello 7’
    > str += " times fast!";
    ’Say hello 7 times fast!’

2. Joining an array of strings. Collect the strings to be concatenated in an array and join it afterwards.

    > var arr = [];
    > arr.push("Say hello ");
    1
    > arr.push(7);
    2
    > arr.push(" times fast");
    3
    > arr.join("")
    ’Say hello 7 times fast’
Which one is faster? Strings being immutable, most string operations whose results are strings produce new strings. Therefore languages such as C# or Java whose string handling is similar to JavaScript’s have special classes that help with concatenating strings. For example, C# calls this class StringBuilder. However, modern JavaScript engines optimize the + operator internally [1]. Tom Schuster mentions Ropes [2] as one possible technique for optimization. Hence there is no need for StringBuilder in JavaScript. Just use += and be done.

References:

  1. Re: String concatenation” – email by Brendan Eich stating that + is faster on modern JavaScript engines.
  2. Ropes: an Alternative to Strings (1995)” by Hans-J. Boehm , Russ Atkinson , Michael Plass.

 

From http://www.2ality.com/2011/10/string-concatenation.html

Deploying code to production can be filled with uncertainty. Reduce the risks, and deploy earlier and more often. Download this free guide to learn more. Brought to you in partnership with Rollbar.

Topics:

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}