Skip to main content

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
console.log(stringLiteral.slice(5,11));
//it will print string"

console.log(stringLiteral);
//"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 ";

console.log(stringObject.newProp);
// Within string object i am a new property

var newStringObject = stringObject;

stringObject.newProp = "I am mutable";

console.log(newStringObject.newProp); 
// I am mutable

Leave a Reply

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