MDN has the following to say about string.concat():

It is strongly recommended to use the string concatenation operators (+, +=) instead of this method for perfomance reasons

Also see the link by @Bergi.

Answer from laktak on Stack Overflow
๐ŸŒ
MDN Web Docs
developer.mozilla.org โ€บ en-US โ€บ docs โ€บ Web โ€บ JavaScript โ€บ Reference โ€บ Global_Objects โ€บ String โ€บ concat
String.prototype.concat() - JavaScript | MDN
The concat() method is very similar to the addition/string concatenation operators (+, +=), except that concat() coerces its arguments directly to strings, while addition coerces its operands to primitives first.
๐ŸŒ
freeCodeCamp
freecodecamp.org โ€บ news โ€บ javascript-string-concatenation
How JavaScript String Concatenation Works โ€“ the "+" Operator vs the "+=" Operator
September 7, 2023 - This method is very handy. When using it, we append separate strings in separate lines. Let me give you an example again. I will use a variable named fullName like earlier, but instead of using the + operator to concatenate strings like earlier, I will use +=:
๐ŸŒ
MDN Web Docs
developer.mozilla.org โ€บ en-US โ€บ docs โ€บ Learn_web_development โ€บ Core โ€บ Scripting โ€บ Strings
Handling text โ€” strings in JavaScript - Learn web development | MDN
You might expect this to return an error, but it works just fine. How numbers should be displayed as strings is fairly well-defined, so the browser automatically converts the number to a string and concatenates the two strings.
Top answer
1 of 4
73

Consider this piece of JavaScript code:

var a = 10;
var b = 20;
console.log('result is ' + a + b);

This will log

result is 1020

Which most likely is not what was intended, and can be a hard to track bug.

2 of 4
49

When you say "bad" do you mean "incorrect" or do you mean "slow"? The argument about using mathematical operators to do string concatenation is arguably an "incorrect" argument, but there's also an argument to be made that using + to do a lot of string concatenation can be very slow.

We're not talking about "Hello" + number when we talk about performance, we're talking about building up a relatively large string by repeatedly appending to it in a loop.

var combined = "";
for (var i = 0; i < 1000000; i++) {
    combined = combined + "hello ";
}

In JavaScript (and C# for that matter) strings are immutable. They can never be changed, only replaced with other strings. You're probably aware that combined + "hello " doesn't directly modify the combined variable - the operation creates a new string that is the result of concatenating the two strings together, but you must then assign that new string to the combined variable if you want it to be changed.

So what this loop is doing is creating a million different string objects, and throwing away 999,999 of them. Creating that many strings that are continually growing in size is not fast, and now the garbage collector has a lot of work to do to clean up after this.

C# has the exact same problem, which is solved in that environment by the StringBuilder class. In JavaScript, you'll get much better performance by building up an array of all the strings you want to concatenate, and then joining them together one time at the end, instead of a million times in the loop:

var parts = [];
for (var i = 0; i < 1000000; i++) {
    parts.push("hello");
}
var combined = parts.join(" ");
๐ŸŒ
2ality
2ality.com โ€บ 2011 โ€บ 10 โ€บ string-concatenation.html
String concatenation in JavaScript
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โ€™ ยท 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.
๐ŸŒ
Codecademy Forums
discuss.codecademy.com โ€บ frequently asked questions โ€บ javascript faq
Is it best practice to use string concatenation or string interpolation? Why? - JavaScript FAQ - Codecademy Forums
August 2, 2018 - Question Is it best practice to use string concatenation or string interpolation? Why? Answer String interpolation was a new feature of ES6 - string interpolation, using template literals, allows us to include variables and expressions in our ...
Find elsewhere
๐ŸŒ
SitePoint
sitepoint.com โ€บ blog โ€บ javascript โ€บ high-performance string concatenation in javascript
High-performance String Concatenation in JavaScript โ€” SitePoint
November 5, 2024 - Both โ€œ+โ€ and โ€œconcat()โ€ can be used for string concatenation in JavaScript, but there are some differences. The โ€œ+โ€ operator is more straightforward and easier to read, but it can lead to confusion if youโ€™re trying to add a number to a string, as JavaScript will try to convert the string to a number.
๐ŸŒ
freeCodeCamp
forum.freecodecamp.org โ€บ t โ€บ which-is-more-efficient-str-some-string-or-array-push-join โ€บ 5802
Which is more efficient str += "some string" or array.push().join()
May 29, 2016 - I know String in JavaScript is immutable which means if I concatenate strings by using +=, a new string will be created with its content being copied from the old string, the old string then gets garbage collected, but โ€ฆ
๐ŸŒ
Hashnode
darshitanjaria.hashnode.dev โ€บ mastering-javascript-the-battle-between-concat-and-template-literals
JavaScript Concat vs. Template Literals: Which One to Use?
April 18, 2025 - The JavaScript engine has to do more work to parse and process template literals, especially if they include embedded expressions or multi-line strings. While this overhead is generally negligible in modern applications, in performance-critical situations or on resource-constrained environments, the direct approach of concat() could be more efficient. ... Here, concat() directly performs the string concatenation without any additional parsing, which might be more optimal in specific cases.
๐ŸŒ
W3Schools
w3schools.com โ€บ jsref โ€บ jsref_concat_string.asp
JavaScript String concat() Method
The concat() method returns a new string. ... let text1 = "Hello"; let text2 = "world!"; let text3 = "Have a nice day!"; let result = text1.concat(" ", text2, " ", text3); Try it Yourself ยป ... If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail: sales@w3schools.com ยท If you want to report an error, or if you want to make a suggestion, send us an e-mail: help@w3schools.com ยท HTML Tutorial CSS Tutorial JavaScript Tutorial How To Tutorial SQL Tutorial Python Tutorial W3.CSS Tutorial Bootstrap Tutorial PHP Tutorial Java Tutorial C++ Tutorial jQuery Tutorial
๐ŸŒ
Reddit
reddit.com โ€บ r/node โ€บ what is the most efficient way to concatenate a string? (for example chat gpt stream responses)
r/node on Reddit: What is the most efficient way to concatenate a string? (For example chat GPT stream responses)
June 17, 2023 -

I have a server that uses the chat gpt api with stream (SSE) and I have to concatenate all the chucks it sends.

I wanted to know if there is something more efficient than +=, in other languages they recommend using a String Buffer, in js/ts I don't know what is best.

Thank you so much.

async function main() {
  const stream = await openai.chat.completions.create({
    model: 'gpt-4',
    messages: [{ role: 'user', content: 'Say this is a test' }],
    stream: true,
  });
  for await (const part of stream) {
    process.stdout.write(part.choices[0]?.delta?.content || '');
  }
}
๐ŸŒ
Reddit
reddit.com โ€บ r/javascript โ€บ why do javascript coders concatenate text using an array and .join()?
r/javascript on Reddit: Why do JavaScript coders concatenate text using an array and .join()?
September 30, 2012 -

I've been working on a project at work and one of the guys that was there before me and supposedly a senior web developer created a whole application with dynamically generated HTML code which looks something like this:

var name = 'Bob';
var text = [];

text.push('Hello ');
text.push(name);
text.push(" how's your day going?");
text.push('My day is going fine thanks ');
text.push(name);

text = text.join('');

Which completely baffled me. I would've thought it was cleaner and more readable to simply do:

var text = '';
var name = 'Bob';

text += 'Hello ' + name + " how's your day going?";
text += 'My day is going fine thanks ' + name;

Is there any reason for using the join() or concatenating the strings like that? I created a jsFiddle and it appears using the array and join() method is 3 times slower.

๐ŸŒ
Educative
educative.io โ€บ answers โ€บ string-concatenation-using-p-operator-vs-template-literals-in-js
String concatenation using + operator vs. template literals in JS
Repeated concatenation using the + operator, with variables and more strings, can lead to a lot of very hard-to-read code.
๐ŸŒ
Scaler
scaler.com โ€บ home โ€บ topics โ€บ 4 ways to concatenate strings in javascript
4 Ways to Concatenate Strings in JavaScript - Scaler Topics
January 6, 2024 - The JavaScript String Concatenation method joins two or more strings without changing the existing strings, hence returning a new string. Learn the methods of String Concatenation here.
๐ŸŒ
Career Karma
careerkarma.com โ€บ blog โ€บ javascript โ€บ javascript concatenate strings: a guide
JavaScript Concatenate Strings: A Guide | Career Karma
December 1, 2023 - The JavaScript concat() method combines two or more strings. concat() accepts as many parameters as you want, each one representing a string to merge. The concat() method is an alternative to the concatenation operator.
๐ŸŒ
Reddit
reddit.com โ€บ r/webdev โ€บ template literals vs string concat.
r/webdev on Reddit: Template Literals vs String Concat.
May 27, 2020 -

Hi, I'm new-ish to web dev, by way of web design, by way of graphic design, so I have a lot to learn. I think maybe I'm missing something re template literals. consider:

return '<h1>Hello ' + firstName + ', welcome to your account.</h1>';

and

return `<h1>Hello '${ firstName }', welcome to your account.</h1>`;

Ok, so you're typing 1 less char, is that the only benefit? Are there performance benefits? It's certainly not significantly more legible or anything. What's the use case where template literals are just far and away superior to plain old string concat?


EDIT: Thanks everyone, I feel like I know when and how to use template literals now.

Top answer
1 of 5
27
Great question! For simple things like your example above, concatenation vs template literals provide very little benefit. Some would argue it's more readable, but that's about it. Template literals get more interesting when you're concatenating multiple variables though, or if you have escaped strings, for example: 'Hello ' + firstName + ', you\'re awesome'; vs Hello ${firstName}, you're awesome`; Minor benefit, but it can be useful. They shine even further though when you have to use multi-line strings (like HTML). A common way to do this before template literals was something like the following (or just appending \n to strings: [ 'Hello', firstName, 'welcome', 'to', 'your', 'account' ].join('\n') vs ` Hello ${firstName,} welcome to your account ` You can also evaluate expressions in template literals, for example `1 + 2 is ${1 + 2}` or `Hello ${firstName || 'unknown'}` etc. And lots lots more . Fundamentally though, it's going to just come down to your preferred coding style, though I imagine as you start concatenating lots of variables you'll quick find template literals great to use. As for performance, don't worry about it. Template Literals and String Concatenation constantly trade blows in browsers with what is faster one week vs the next week, but realistically they're both so fast and the variation between them is so minimal that it's almost certainly never going to be a bottleneck in your application.
2 of 5
7
In your template-literal example you don't need the single-quotes around the variable: so it's

Hello ${firstName}, welcome to your account.

; -- so it is a little easier to write and read. Opening and closing your strings a bunch of times can get tiresome. Also you can have any number of line breaks inside a template literal, which is a heck of a lot easier than having to close your string and add a + on every new line if you're using string concatenation on a big block of HTML. But point taken, string concatenation still works just fine if you prefer it. And it works on all browsers, which isn't true for template literals, so that's good too.
Top answer
1 of 6
137

With ES6, you can use

  • Template strings:

    var username = 'craig';
    console.log(`hello ${username}`);
    

ES5 and below:

  • use the + operator

    var username = 'craig';
    var joined = 'hello ' + username;
    
  • String's concat(..)

    var username = 'craig';
    var joined = 'hello '.concat(username);
    

Alternatively, use Array methods:

  • join(..):

    var username = 'craig';
    var joined = ['hello', username].join(' ');
    
  • Or even fancier, reduce(..) combined with any of the above:

    var a = ['hello', 'world', 'and', 'the', 'milky', 'way'];
    var b = a.reduce(function(pre, next) {
      return pre + ' ' + next;
    });
    console.log(b); // hello world and the milky way
    
2 of 6
29

I'm disappointed that nobody in the other answers interpreted "best way" as "fastest way"...

I pulled the 2 examples from here and added str.join() and str.reduce() from nishanths's answer above. Here are my results on Firefox 77.0.1 on Linux.


Note: I discovered while testing these that if I place str = str.concat() and str += directly before or after each other, the second one always performs a fair bit better... So I ran these tests individually and commented the others out for the results...

Even still, they varied widely in speed if I reran them, so I measured 3 times for each.

1 character at a time:

  • str = str.concat(): 841, 439, 956 ms / 1e7 concat()'s
  • ............str +=: 949, 1130, 664 ms / 1e7 +='s
  • .........[].join(): 3350, 2911, 3522 ms / 1e7 characters in []
  • .......[].reduce(): 3954, 4228, 4547 ms / 1e7 characters in []

26 character string at a time:

  • str = str.concat(): 444, 744, 479 ms / 1e7 concat()'s
  • ............str +=: 1037, 473, 875 ms / 1e7 +='s
  • .........[].join(): 2693, 3394, 3457 ms / 1e7 strings in []
  • .......[].reduce(): 2782, 2770, 4520 ms / 1e7 strings in []

So, regardless of whether appending 1 character at a time or a string of 26 at a time:

  • Clear winner: basically a tie between str = str.concat() and str +=
  • Clear loser: [].reduce(), followed by [].join()

My code, easy to run in a browser console:

{
  console.clear();

  let concatMe = 'a';
  //let concatMe = 'abcdefghijklmnopqrstuvwxyz';

  //[].join()
  {
    s = performance.now();
    let str = '', sArr = [];
    for (let i = 1e7; i > 0; --i) {
      sArr[i] = concatMe;
    }
    str = sArr.join('');
    e = performance.now();
    console.log(e - s);
    console.log('[].join(): ' + str);
  }

  //str +=
  {
    s = performance.now();
    let str = '';
    for (let i = 1e7; i > 0; --i) {
      str += concatMe;
    }
    e = performance.now();
    console.log(e - s);
    console.log('str +=: ' + str);
  }

  //[].reduce()
  {
    s = performance.now();
    let str = '', sArr = [];
    for (let i = 1e7; i > 0; --i) {
      sArr[i] = concatMe;
    }
    str = sArr.reduce(function(pre, next) {
      return pre + next;
    });
    e = performance.now();
    console.log(e - s);
    console.log('[].reduce(): ' + str);
  }

  //str = str.concat()
  {
    s = performance.now();
    let str = '';
    for (let i = 1e7; i > 0; --i) {
      str = str.concat(concatMe);
    }
    e = performance.now();
    console.log(e - s);
    console.log('str = str.concat(): ' + str);
  }

  'Done';
}