JavaScript String Immutability with Example and Output

In Javascript, Strings are Immutable which means their value cannot be changed over time. Example below:

 //String Immutability


var strs = new String("Test");
console.log(strs); // [String: 'Test']
var strs1 = "Test";
console.log(strs1); //Test

strs.concat("1234");
console.log(strs); // [String: 'Test']
strs1.concat("1234");
console.log(strs1); //Test

To perform any changes we need to use strings as in example below:

//To perform any changes
strs = strs.concat("1234");
console.log(strs); //Test1234
strs1 = strs1.concat("1234");
console.log(strs1); //Test1234

We'll have a look at few String methods in my next post.

Comments