JavaScript strings are immutable objects means once a String object is assigned to a String reference the object value cannot be changed.
You can’t change a character within a string with something like:
var myString = "abcdef";
myString[0] = 'c';
String manipulation methods such as trim
, slice
return new strings.
In the same way, if you have two references to the same string, modifying one doesn’t affect the other
let a = b = "hello";
a = a + " world";
// b is not affected
JavaScript string immutable
Simple example code.
<!DOCTYPE html>
<html lang="en">
<body>
<script>
let string1 = 'hello';
let string2 = string1;
console.log('string1 ->', string1);
console.log('string2 ->', string2);
console.log('string1 === string2 ->', string1 === string2); // true
string1.concat(' world!');
console.log('string1 ->', string1); // still just 'hello', because `concat` doesn't (and cannot) mutate the original string
string1 = string1.concat(' world!'); // change by reassignment
console.log('string1 ->', string1); // *now* it reflects the change
// but now string 1 and string 2 are different
console.log('string1 ->', string1);
console.log('string2 ->', string2);
// and not equal
console.log('string1 === string2 ->', string1 === string2);
// also, since they are immutable, strings are just compared by *value*, so we can do this
console.log('"hello" === string2 ->', "hello" === string2); //true
</script>
</body>
</html>
Output:
Implications of Immutability
Performance Considerations: Since operations on strings create new strings, repeated modifications in a loop can lead to performance issues due to the creation of many intermediate strings. Using an array to build a large string and then joining the array elements can be more efficient.
let str = "";
for (let i = 0; i < 1000; i++) {
str += "a"; // Creates new string each time
}
// More efficient approach
let arr = [];
for (let i = 0; i < 1000; i++) {
arr.push("a");
}
let efficientStr = arr.join("");
Predictability and Safety: Immutability ensures that a string cannot be accidentally changed by other parts of the code, leading to more predictable behavior and fewer bugs.
Do comment if you have any doubts or suggestions on this JS string topic.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version