Strings are not just arrays of characters
Immutability, encoding and the concatenation trap that turns O(n) into O(n²).
Strings look like character arrays and behave differently in three ways that cause real bugs.
They are immutable
Every "modification" builds a new string. Inside a loop that is quadratic:
// O(n²): each += copies the whole string so far.
let out = '';
for (const ch of text) out += transform(ch);
// O(n): collect, then join once.
const parts = [];
for (const ch of text) parts.push(transform(ch));
const result = parts.join('');
Modern engines optimise some += patterns with ropes, but the array-and-join version is the one that is portable and predictable. In Java it is StringBuilder; in Python ''.join(parts); in Go strings.Builder.
A character is not a code unit
JavaScript strings are UTF-16. Anything outside the basic plane — emoji, many CJK extensions — occupies two code units, and length counts units, not characters.
'😀'.length; // 2
'😀'[0]; // half a surrogate pair, meaningless alone
[...'😀'].length; // 1 — the spread iterates code points
Reversing a string with split('').reverse().join('') corrupts every emoji in it. Use [...text] when correctness for real user input matters.
Comparison is not always byte comparison
Accented characters can be composed of a base plus a combining mark, or a single precomposed code point. The two render identically and are not ===. Normalise before comparing user text:
'é'.normalize('NFC') === 'é'.normalize('NFC');
For case-insensitive comparison, toLowerCase() is locale-dependent for a handful of languages — Turkish dotless i being the standard example.
Costs to keep in mind
| Operation | Cost |
|---|---|
charAt, index access |
O(1) |
slice, substring |
O(k) for the copy |
includes, indexOf |
O(n × m) worst case |
| Concatenation in a loop | O(n²) unless you join |
| Sorting characters of a string | O(n log n) — the usual anagram key |
Two anagrams share a sorted-character key, and grouping anagrams is exactly a hash map keyed on that. Which is the next chapter's territory.