Why are strings immutable in JavaScript?
It cuts both ways. Because a string can never change, the engine can store one copy and share it between every variable that holds the same value. Interning, which is the automatic sharing of identical string literals, means the engine can spot two equal literals while it compiles and point both at the same memory. That is why comparing two equal strings is cheap.
const a = 'hello';
const b = 'hello';
console.log(a === b); // true - the same primitive value
// Repeated concatenation allocates a new string every time.
let out = '';
for (let i = 0; i < 1000; i++) {
out += 'ab';
}
console.log(out.length); // 2000
// Collecting the pieces and joining once is usually faster.
const pieces = [];
for (let i = 0; i < 1000; i++) {
pieces.push('ab');
}
console.log(pieces.join('').length); // 2000
The cost of immutability is memory. Every change gives you a new string, and the old one becomes rubbish for the collector to clean up. Repeated concatenation inside a loop is the classic example, and because every step copies the whole string that has been built so far, the total work grows with the square of the length.
Modern engines partly hide this with a rope representation, where a long string is stored as a tree of smaller pieces and it is only flattened when something needs the characters one at a time. That makes concatenation much cheaper than it used to be, but it does not remove the allocation, and the flattening cost still has to be paid eventually.
The practical advice is short. For a few joins, do not worry about it. For building a large string inside a loop, push the pieces into an array and join them once. And if you are adding to a string again and again, a list is the right data structure instead of a string. The third question in this topic looks at what really happens when you try to modify a string in place.