Why are strings immutable in JavaScript?
Because strings are values, and values are not supposed to change behind your back. If a string could be edited in place, then two variables holding the same string could end up with different contents, and you would have no way to know which one you were reading. Making strings immutable means the value you have is the value you will always have.
const original = "hello";
const changed = original.toUpperCase();
console.log(original); // "hello"
console.log(changed); // "HELLO"
// Assigning to an index does nothing.
original[0] = "H";
console.log(original); // "hello"
// Strings are compared by value.
console.log("a" + "b" === "ab"); // trueThat safety is what lets the engine optimise aggressively. Because a string can never change, the engine can share one copy between every variable that holds the same value, cache the result of a property lookup keyed by that string, and use the string as a key in a map without worrying about the key being modified behind it. Hashing a string for a map lookup would be much more expensive if the string could change while it was in the map.
Immutability also removes a whole class of bugs in concurrent code. If two parts of a program share a string, neither can change what the other one sees. There is no need to copy before handing a string to a function, because the function cannot change it.
The cost is that every change allocates. Building a long string by repeated concatenation creates a new string each time, and the earlier ones become garbage. That is the performance reason to collect pieces in an array and join once, rather than concatenating in a loop.