Understanding String Immutability in JavaScript
In JavaScript, strings are immutable, meaning they cannot be changed once they are created. This fundamental concept ensures that any modification to a string results in the creation of a new string, leaving the original unchanged.
What Does Immutability Mean?
In JavaScript, all strings are immutable.
Immutable means that an existing string cannot be altered.
No direct modifications can be made to strings.
Whenever we try to modify a string, a new string is created while the old one remains unchanged.
When we apply a method to a string or perform an operation on it, a new string is created instead of modifying the existing one.
Example of String Immutability
Consider the following example where we use the .trim()
method to remove extra spaces from a string:
Code Example
let msg = " inder ";
console.log(msg.trim());
Console Output
"inder"
Even though .trim()
appears to modify the msg
string, it actually creates a new string with spaces removed. The original msg
variable still holds the same value.
Understanding Through Another Example
let text = "Hello";
text.toUpperCase();
console.log(text);
Output:
"Hello"
Even though we applied .toUpperCase()
, the text
variable remains unchanged because strings are immutable. To actually store the modified value, we need to assign it to a new variable:
let newText = text.toUpperCase();
console.log(newText);
New Output:
"HELLO"
Key Takeaways
Strings in JavaScript cannot be modified directly.
Any modification results in a new string being created.
To work with modified strings, we must store them in a new variable.
This behavior is important for memory efficiency and helps prevent accidental changes to existing data.