Immutability with Spread Method
Wanna enforce immutability? Don’t use push() method ! Because it mutates state || object || array. Avoid this mistake and try something better: concat(), slice() or as an example, spread operator ...
for arrays and Object.assign() for objects.
Spread Operator
For example, you wanna have an array myArray
and write:
let newArray = [...myArray];
newArray
is now a clone of myArray
.
Both arrays still exist separately in memory. If you perform a mutation like newArray.push(5)
, myArray
doesn't change. The ...
effectively spreads out the values in myArray
into a new array. To clone an array but add additional values in the new array, you could write [...myArray, 'new value']
. This would return a new array composed of the values in myArray
and the string 'new value'
as the last value.
Conclusion
Wanna know how other methods work? Follow me and I’ll make an introduction to you. It’s as easy as pie:)