Concatenate strings in a loop efficiently in JavaScript
Beginner · 4 min read
Putting strings together is something you do constantly: a full name from first and last, a line of output from several values, a big piece of text built up in a loop. JavaScript gives you several ways to do it, and beginners often wonder which one is "right" or fastest.
In this tutorial you will join strings four ways: the concat method, the + operator, += inside a loop, and collecting pieces in an array and joining once. You will also see that none of them changes the original string. You should know what a loop and an array are.
Strings can't be changed
A string in JavaScript is immutable: once it exists, it can never be changed. Every method that seems to change a string, like toUpperCase or replace, actually makes a new one and leaves the old one alone.
So "adding to a string" always means making a new, longer string. Keep that in mind; it explains every result below.
Joining is called concatenation
The word concatenate means to link things together end to end. That is why the method is called concat, and why joining with + is called string concatenation.
Here is the exercise. Try it yourself first if you like, or read on and we will build it step by step.
33 concat, plus, and building up in a loop
easyJoin strings four ways: with concat, with +, with += in a loop, and by collecting pieces and joining once. Confirm the original is never modified.
Stuck? Three hints, smallest first
- 1.
concattakes any number of arguments and converts each one. - 2.
+=creates a new string every time round the loop; it never appends in place. - 3. Collecting into an array and joining once is the habit that scales.
Step 1: the concat method
console.log('a'.concat('b')); // 'ab'
console.log('a'.concat('b', 'c', 'd')); // 'abcd'
console.log('n='.concat(42)); // 'n=42'
console.log('a'.concat()); // 'a'
concat takes any number of arguments and adds them to the end, in order. A number is turned into text first. With no arguments you just get the same text back.
Step 2: the + operator
console.log('a' + 'b' + 'c' + 'd'); // 'abcd'
Same result, shorter to type and easier to read. In practice most people use + or a template literal, and concat is rarely seen. It does exactly the same job.
Step 3: += in a loop
When the pieces come from a loop, a common pattern is to start with an empty string and add to it each time round:
const pieces = ['a', 'b', 'c'];
let out = '';
for (const c of pieces) out += c.toUpperCase();
console.log(out); // 'ABC'
out += x is short for out = out + x. Because strings are immutable, each step makes a new string and points out at it. The old one is thrown away.
Step 4: collect, then join once
The other approach is to build an array of finished pieces and join them at the end:
const pieces = ['a', 'b', 'c'];
const byJoin = pieces.map((c) => c.toUpperCase()).join('');
console.log(byJoin); // 'ABC'
map makes a new array with each piece changed, and join('') glues them together once. This keeps the two jobs apart: first change each piece, then assemble. It also makes separators easy. Change join('') to join(', ') and you get 'A, B, C', with no stray comma at the end to clean up.
Step 5: which one is faster?
You may read that += in a loop is slow because it makes a new string every time. Modern JavaScript engines handle this case well, so for normal amounts of text the difference doesn't matter. Pick the one that reads best. For building text from a list, map and join is usually the clearest.
Step 6: the original never changes
const a = 'x';
const b = a.concat('y');
console.log(a, b); // x xy
let c = a;
c += 'y';
console.log(a, c); // x xy
concat returned a new string and left a alone. And c += 'y' didn't change the string 'x' either. It made a new string 'xy' and pointed c at it, while a still points at 'x'.
The full solution
Here is the complete answer: concat with several arguments, +, the += loop and the map-then-join version, plus checks that the originals are unchanged. Press Run to see the loop and join results side by side.
const pieces = ['a', 'b', 'c'];
const byLoop = (() => {
let out = '';
for (const c of pieces) out += c.toUpperCase();
return out;
})();
const byJoin = pieces.map((c) => c.toUpperCase()).join('');
console.log("'a'.concat('b', 'c', 'd') :", 'a'.concat('b', 'c', 'd'));
console.log('byLoop :', byLoop, ' byJoin :', byJoin);
console.log('strings are immutable, so every step makes a new one');
Output
10 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 10 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('concat joins strings', 'a'.concat('b'), 'ab');
test('and takes several arguments', 'a'.concat('b', 'c', 'd'), 'abcd');
test('plus does the same and reads better', 'a' + 'b' + 'c' + 'd', 'abcd');
test('concat converts its arguments', 'n='.concat(42), 'n=42');
test('concat with no arguments returns a copy', 'a'.concat(), 'a');
test('an array of pieces is better joined', pieces.join(''), 'abc');
test('+= in a loop works', byLoop, 'ABC');
test('and map-then-join gives the same answer', byJoin, 'ABC');
test('strings are immutable, so concat returns a new one', (() => { const a = 'x'; const b = a.concat('y'); return [a, b]; })(), ['x', 'xy']);
test('and += rebinds rather than modifying', (() => { const a = 'x'; let b = a; b += 'y'; return a; })(), 'x');
All four produce identical strings, so choose on readability. concat is the one with no advantage: it is longer than + and slower to read.
The "+= in a loop is slow" advice is largely obsolete — engines optimise it heavily with rope representations — but map then join is still the better default, because it separates the transformation from the assembly and it works when the separator is not empty.
Common mistakes
- Calling
concatand ignoring the result.name.concat('!')on its own line does nothing. Assign it. - Leaving a trailing separator.
out += c + ', 'in a loop ends with', '. Collect the pieces and usejoin(', '). - Using
constwith+=.const out = ''; out += 'a'throws aTypeError, because+=reassigns the variable. Uselet.
Try it yourself
- Build
'1-2-3-4-5'from the numbers 1 to 5, once with a+=loop and once withjoin. - Use
concatto join a first name, a space and a last name in one call. - Turn
['tea', 'bread', 'eggs']into a numbered list, one item per line:'1. tea','2. bread','3. eggs'.