Why can't you fix a string?
Why text[0] = "C" does nothing, and string methods always return a new string.
let headline = "Bat eats sausage";
headline[0] = "C";
console.log(headline);Strings in JavaScript are immutable. Once created, a string can't change by a single letter. Every "change" is the creation of a new string based on the old one.
let headline = "Bat eats sausage";
headline = "C" + headline.slice(1);
console.log(headline);Why is it designed this way? Three reasons.
1. Safe sharing. One string can be passed to ten functions, and none can spoil it for the others. Arrays aren't like that: a push in one place shows up everywhere.
2. Strings are keys. Strings serve as keys of objects and Maps. If a key could change, it could no longer be found afterwards.
3. Savings. Since a string never changes, the engine can keep one copy of identical strings and not copy them when passing them around.
Hence the main rule of working with strings: store the method's result. title.trim(), title.toUpperCase(), title.replace(…) all return a new string and leave the original alone.
Myth or fact?
Decide whether the statement is true. Got it wrong? Try again; once you're right, Byte explains what's going on.