Are strings mutable in JavaScript?
No. Strings are immutable primitives. Methods like toUpperCase, slice and replace never change the original; they return a new string, so you must assign or use the result.
Explain it simply
A printed railway ticket cannot be edited. If the name is wrong, a new ticket is printed. Strings in JavaScript work like that: once created, their characters never change.
Every string method that looks like it edits, such as toUpperCase(), trim(), replace() or slice(), actually builds and returns a new string. If you do not store or use the result, the work is thrown away. Even s += "!" creates a new string and points s at it, which is why another variable holding the old string is unaffected.
You can read characters with s[0], but you cannot assign to them.
Example
let s = "india";
s.toUpperCase();
console.log(s); // Output: india
s = s.toUpperCase();
console.log(s); // Output: INDIA
const copy = s;
s += "!";
console.log(copy); // Output: INDIA
console.log(s); // Output: INDIA!
console.log("india"[0]); // Output: iWhat to say in the interview
"Strings are immutable primitives. Their methods return new strings and leave the original untouched, so I always capture the return value. Repeated concatenation in a loop creates many intermediate strings, so for big joins I build an array and call join."
Common mistakes
- Calling str.trim() or str.replace() and ignoring the returned value.