Sub topic 16
Building Strings Efficiently
This chapter assumes you know template literals, split and join, padStart and repeat, and how values are converted to strings, all from earlier chapters. You should also be comfortable with array methods such as map and with running code in Node.js or a browser console. The chapter covers how to assemble larger strings from many pieces, what JavaScript engines do behind the scenes when you concatenate, and which mistakes cause wrong output or slow code.
The Building Blocks
There are four common ways to combine strings. All four produce the same result for simple input.
const parts = ["a", "b", "c"];
let s1 = "";
for (const p of parts) s1 += p; // repeated concatenation
const s2 = parts.join(""); // array join
const s3 = "".concat(...parts); // String.prototype.concat
const s4 = `${parts[0]}${parts[1]}${parts[2]}`; // template literal
console.log(s1, s2, s3, s4); // abc abc abc abcStrings are immutable, so each of these creates a new string and leaves the inputs unchanged. You might expect s1 += p to copy the whole accumulated string on every pass, which would make a loop of n appends cost O(n²). That was true in some older engines. Modern engines avoid most of that cost, as the next section explains.
How Engines Handle Concatenation Internally
V8 (Chrome, Node.js), SpiderMonkey (Firefox), and JavaScriptCore (Safari) all use a structure usually called a rope. When you write a + b and the result is long enough, the engine allocates a small node that points to a and b. It does not copy any characters. Repeated += therefore builds a tree of these nodes cheaply.
The characters are copied only when something needs a flat, contiguous string. Examples include indexing with s[i], calling charCodeAt, running a regular expression, or passing the string to a native API. This copy is called flattening. It costs O(total length) once, and the engine then caches the flat result.
The practical effect is that appending in a loop is usually fast. One pattern is still slow: alternating appends with reads. If every iteration does s += x and then also looks at s[s.length - 1] or runs s.includes(...), the engine may flatten on every pass. That brings back the quadratic cost.
Measuring Instead of Guessing
The following script builds the same 200,000-line string in two ways and times both.
function withPlus(n) {
let out = "";
for (let i = 0; i < n; i++) out += "row " + i + "\n";
return out;
}
function withJoin(n) {
const rows = [];
for (let i = 0; i < n; i++) rows.push("row " + i);
return rows.join("\n") + "\n";
}
function time(label, fn) {
const t0 = performance.now();
const result = fn();
const ms = performance.now() - t0;
console.log(label, result.length, ms.toFixed(1) + " ms");
}
time("+= ", () => withPlus(200000));
time("join", () => withJoin(200000));Both lines print the same length. On current Node.js the two times are usually close, and += is often slightly faster because it never allocates the intermediate array. Run each version several times, because the first run includes JIT warm-up. Single runs of microbenchmarks are noisy.
When join is still the better choice
join is the clearer choice when the pieces already exist as an array or are produced by map. It also handles separators correctly with no extra code. Loops that use += with a separator tend to leave a trailing separator, or they need an if (i > 0) check. join puts separators only between elements.
Gotchas in Concatenation
Most string-building bugs are wrong output, not slow code. The + operator and template literals convert values in slightly different ways.
console.log("Total: " + 1 + 2); // Total: 12
console.log("Total: " + (1 + 2)); // Total: 3
console.log(1 + 2 + " items"); // 3 items
console.log([null, undefined, 0, "x"].join("-")); // --0-x
const price = {
valueOf() { return 42; },
toString() { return "$42.00"; },
};
console.log("" + price); // 42
console.log(`${price}`); // $42.00
console.log(String(price)); // $42.00
try {
console.log("id: " + Symbol("k"));
} catch (e) {
console.log(e.constructor.name); // TypeError
}
console.log(String(Symbol("k"))); // Symbol(k)Here is what each case shows:
- Left-to-right evaluation.
+groups from the left. Once one operand is a string, every later+concatenates. Put arithmetic in parentheses. - join drops null and undefined. They become empty strings, unlike
String(null), which gives"null". This can hide missing data in CSV output. - The two conversions use different hints.
"" + objconverts with the "default" hint, which triesvalueOffirst. A template literal andString()use the "string" hint, which triestoStringfirst. Objects that define both methods can give different text depending on which syntax you use. - Symbols. Implicit conversion of a Symbol throws a
TypeError, in both+and template literals. OnlyString(sym)orsym.descriptionwork.
| Technique | Best for | Watch out for |
|---|---|---|
| `+` / `+=` | Short expressions and simple loops | Numeric operands added before concatenation, valueOf hint |
| Template literal | Mixing fixed text with values | Calls toString; throws on Symbol |
| `array.join(sep)` | Lists with separators, output of `map` | null and undefined become `""` |
| `"".concat(...)` | Rarely needed | Spreading very large arrays can exceed the argument limit |
| `repeat`, `padStart`, `padEnd` | Fixed-width fill and alignment | `repeat` throws on negative or infinite counts |
A Practical Pattern: Map, Then Join
To produce formatted output such as reports, HTML fragments, or log blocks, map each record to a line, then join the lines. Each line is built from one template literal, and padding takes care of alignment.
const rows = [
{ name: "alice", score: 92 },
{ name: "bob", score: 7 },
{ name: "carol", score: 85 },
];
const width = Math.max(...rows.map((r) => r.name.length));
const header = `${"name".padEnd(width)} | ${"score".padStart(5)}`;
const rule = "-".repeat(header.length);
const body = rows
.map((r) => `${r.name.padEnd(width)} | ${String(r.score).padStart(5)}`)
.join("\n");
console.log([header, rule, body].join("\n"));
// name | score
// ------+------ (all dashes in the actual output)
// alice | 92
// bob | 7
// carol | 85The rule line is printed as 13 dashes. The comment above only shows where the column break falls. The pattern has no mutable accumulator, no trailing-separator bug, and each line can be tested on its own.
Very Large Output
Every string has to fit in memory, and engines cap string length. V8 allows roughly 2²⁹ UTF-16 code units, about 1 GB, on 64-bit builds. Building a multi-gigabyte export into one string fails with RangeError: Invalid string length. For large output:
- Write it in chunks to a stream (
process.stdout.write, a file stream, or aReadableStreamin the browser) instead of accumulating it. - Join in batches. Build a few thousand lines, write them, and clear the array.
- Prefer
joinover"".concat(...hugeArray). Spreading a huge array passes every element as a separate argument and can throw aRangeErrorfor exceeding the call-stack size.
Choosing an Approach
- For a handful of values with fixed text, use a template literal.
- For a list with separators, or when the data is already an array, use
mapthenjoin. - For a loop that only appends,
+=is fine on modern engines. Don't read from the accumulator inside the loop. - For output too large to keep in memory, stream it in chunks.
- When performance matters, measure on the real runtime with realistic data sizes.
Exercise
This function returns "a,b,c," with a trailing comma, and it also checks the accumulator on every iteration. Rewrite it to return "a,b,c" without either problem, and explain why the original could be slow for large inputs. function csv(items) { let out = ""; for (const it of items) { out += it + ","; if (out.endsWith(",,")) throw new Error("empty item"); } return out; }
Show answer
Validate the items, then join them: function csv(items) { if (items.some((it) => it === "")) throw new Error("empty item"); return items.join(","); }. The original calls endsWith on the accumulator after every append. That read can force the engine to flatten its rope representation on every iteration, which turns cheap O(1) appends into repeated O(n) copies and gives quadratic total cost. join puts separators only between elements, so no trailing comma appears.
Exercise
Given const t = { valueOf: () => 7, toString: () => "seven" };, what do "x" + t, ` x${t} , and ["x", t].join("")` each produce, and why?
Show answer
"x" + t gives "x7", because + converts with the default hint and calls valueOf first. ` x${t} gives "xseven", because template literals use ToString, which calls toString first. ["x", t].join("")` gives "xseven", because join converts each element with ToString.
Exercise
Why does "Count: " + 2 + 3 print "Count: 23", and what are two ways to get "Count: 5"?
Show answer
+ is evaluated left to right. "Count: " + 2 is the string "Count: 2", and adding 3 to a string concatenates. Use parentheses, as in "Count: " + (2 + 3), or a template literal, as in ` Count: ${2 + 3} `.