Javascript String Immutability
This blog discusses String immutable property and covers a basic overview.
String in Javascript
The string helps us in storing a sequence of characters. Like the name, address, paragraph, etc.
Get Sachin Sarawgi’s stories in your inbox
Join Medium for free to get updates from this writer.
String individual characters are accessed using square brackets ‘[]’, mentioning the index of the character. String characters are zero-index based which means the first character is at index 0, second at 1, third at 2 and simultaneously.
String Immutability
Javascript String is immutable, which means once a String object is assigned to String reference the object value cannot be changed. However, we can still assign a new object to a String reference.
var myVar = "Hello World";
myVar.toUpperCase();One may think after the first line the myVar will become “HELLO WORLD”, but it still equals to “Hello World”. The method will return a new String object it will not change the existing String reference. So we have to assign it to a new variable to get the desired value.
var myVarUpperCase = myVar.toUpperCase();It may seem that once a String reference is assigned to a String object it cannot be reused as we can't change the value but we can assign existing String reference a new String object altogether.
var myVar = "Hello World";
myVar = "Hello World!!!!"; //new String reference assigned//this will assign return new String reference to myVar object.
myVar = myVar.toUpperCase();
Note: We also cannot assign a new character to an index in String by square bracket notation. As Strings are immutable, by doing that we will be updating the content of String reference which cannot be possible in case of immutability.
var myVar = "Hello";
myVar[0] = "i";//still myVar remains same.String object has many methods which deal with string characters and all of them returns a new String object instead of modifying the String object on which they are called.
Reached till here, give me follow up to get the latest stories.
If you enjoyed reading this, don’t forget the applause. 👏
Thank you.






