Immutability in Javascript…..

The string type (primitive type) value is immutable that means you cannot change

its value without reassign. No string method can change its value its only create another one. In example

var stringLiteral = 'I am string literal and I am immutable';

//Firstly using method
//it will print string"

//"I am string literal and 
//I am immutable its value remain unchange

//and secondly we can not add method in string literal

stringLiteral.prop = "I am new method";

console.log(stringLiteral.prop); // ->; undefined

But the String object, which is created by using the new String() constructor, is mutable, because it is an object and you can add new properties to it

var stringObject = new String('I am string literal and I am mutable');

// on the others side 
// we can add a new property in string object

stringObject.newProp = "Within string object i am a new property ";

// Within string object i am a new property

var newStringObject = stringObject;

stringObject.newProp = "I am mutable";

// I am mutable

Leave a Reply

Your email address will not be published. Required fields are marked *