Immutability
immutability means that you cannot change the value or state of an object.
the string value is immutable but the string object is mutable
if you try to change the string value through indexing like an array javascript will throw you an error. However you can access the value through indexing in read-only mode. This allows you to copy the value in the index into another variable.
When you want to modify a string you use methods like replace(),toUpperCase(),trim()
. All of these methods don't change the original string. They copy the string and create a new string that is modified.
reference equality vs value equality
the equality sign can have two meanings, that the value within the variable is equal or that the reference that the variables are refering to are equal.
var str1 = ‘abc’;
var str2 = str1;
str1 === str2 // true
In the case above the two variables are both refering to the same reference. They are pointers.
Since str1 is pointing to the memory address that is containing abc and str2 is storing the address they have reference equality.
var str1 = ‘abc’;
var str2 = ‘abc’;
str1 === str2 // true
var n1 = 1;
var n2 = 1;
n1 === n2 // also true
This can also be true if they are refering to immutable values.
Strings as mentioned above are immutable data types. Since string values are immutable and integer values are also immutable str1 and str2, n1 and n2 have reference equality
var str1 = new String(‘abc’);
var str2 = new String(‘abc’);
str1 === str2 // false
var arr1 = [];
var arr2 = [];
arr1 === arr2 // false
However this becomes more complicated if you go into the subject of objects. Object point to a space in memory that has a container. So you can change the value of the different components that the object has while not changing the object itself.
var str1 = new String(‘abc’);
var str2 = new String(‘abc’);
str1.valueOf() === str2.valueOf() // true
str1.trim() === str2.trim() // true
So how do you implement immutability?
You have to copy the information within the element and put it into a new element.
The first way is creating a completely new element manually
const modifyShirt = (shirt, newColor, newSize) => {
return {
id: shirt.id,
desc: shirt.desc,
color: newColor,
size: newSize
};
}
The second way is by using Object.assign
const modifyShirt = (shirt, newColor, newSize) => {
return Object.assign( {}, shirt, {
color: newColor,
size: newSize
});
}
The third way is by using the spread operator
const modifyShirt = (shirt, newColor, newSize) => {
return {
...shirt,
color: newColor,
size: newSize
};
}
const addValue = (arr) => {
return [...arr, 1];
};