Sub topic 16
Building Strings Efficiently
This chapter assumes you know that strings are immutable and that you can use template literals, split, join, and array methods such as map. It covers the common ways to put a large string together from small pieces, and the mistakes that tend to come up along the way.
The working model
A string never changes after it is created, so result += piece makes a new string each time. In theory a loop of += copies more text on every pass. In practice, engines such as V8 store repeated concatenations as a rope, which is a tree of pieces that holds references to the parts instead of copying them. The engine flattens the rope into one block of memory only when you read the characters, for example by indexing it or passing it to includes. For most loops, += is fast.
How you build a string therefore matters more for correctness and readability than for speed. There are three common patterns:
| Pattern | Best for | Typical mistake |
|---|---|---|
| `+=` in a loop | Simple append with conditions in the loop | Leftover trailing separators |
| Collect into an array, then `join` | Items that need a separator | Forgetting that `join()` defaults to `","` |
| Template literal | A fixed shape with a few values | Values that are `undefined` print as `"undefined"` |
Comparing the patterns
const rows = [
{ name: "alice", score: 90 },
{ name: "bob", score: 7 },
{ name: "carol", score: 42 },
];
// 1. += in a loop: works, but needs care with separators
let csv = "";
for (const r of rows) {
csv += r.name + ",";
}
console.log(csv); // alice,bob,carol, (trailing comma)
// 2. Collect, then join once: separators only go between items
const names = rows.map((r) => r.name);
console.log(names.join(",")); // alice,bob,carol
// 3. Template literal for each line, join for the list
const report = rows
.map((r) => `${r.name.padEnd(6)}${String(r.score).padStart(3)}`)
.join("\n");
console.log(report);
// alice 90
// bob 7
// carol 42
// Repeated content: use repeat instead of a loop
console.log("-".repeat(9)); // ---------The join version avoids a whole class of off-by-one bugs, because join puts the separator only between elements. It also keeps the transformation (map) apart from the assembly (join), and each step is easier to test on its own.
Common errors
- Trailing or leading separators. These come from appending
","inside a loop. Usejoininstead of trimming the extra character off afterwards. undefinedandnullin output. Template literals andjoinbehave differently here. `${undefined}gives"undefined", but[undefined, null].join("-")gives"-", becausejoin` turns those values into empty strings. Check optional values before you interpolate them.- Objects in output. `
${{ a: 1 }}gives"[object Object]". UseJSON.stringify` or pick out the fields you need. - Reading inside the build loop. Calling
result.lengthorresult.includes(...)on every pass makes the engine flatten the rope again and again. Do the checks on the parts, or after the loop has finished. - Optimizing too early. Pick the clearest pattern first. Measure with real data before you rewrite
+=code for speed.
Exercise
This code prints "a; b; c; ". Rewrite it so it prints "a; b; c" without trimming the result afterwards: let out = ""; for (const x of ["a", "b", "c"]) { out += x + "; "; }
Show answer
Put the parts in an array and join them: const out = ["a", "b", "c"].join("; "); The join method adds the separator only between elements, so there is no separator at the end.
Exercise
What does ${undefined} and ${null} produce, and what does [undefined, "x", null].join("|") produce?
Show answer
The template literal produces "undefined and null". The join call produces "|x|", because join turns undefined and null into empty strings.