In this article, I’ll focus on showing how to add, edit and remove items in an array causing mutation and non-mutation ways.
One thing we need to keep in mind when writing code avoiding mutation is to return a new reference to the data after the update.
It’s a common approach when working with functional programming and if you want to understand some concepts of functional programming I recommend you read this article I wrote some time ago.
Why Avoid Mutation
When you work with immutable data you can have some positive impacts like the following:
– Tracking data without mutation is much better;
– Immutable states help you implement unidirectional data flow that helps you handle data;
I really recommend you read this article to go deeper into why avoid mutation.
Causing Mutation
The following steps will cause mutation into the array when adding, removing and editing elements from `family`.
To show an example of mutating, we’ll use the following array:
See that in all the examples that we developed above, a new instance of the array was created, thus avoiding the mutation of the initially defined arrays.
Wrapping Up
Avoiding mutations is a safe and one-way path.
When you realize that you’re writing code observing this type of detail, believe me, you will be writing better, secure code and avoiding possible bugs due to mutation.
Feel free to share your feedback and experience in the comments.
Why should mutation be avoided when working with arrays?
Avoiding mutation offers positive impacts such as better data tracking without mutation, and immutable states that help implement unidirectional data flow, which makes handling data easier.
Which array methods cause mutation when adding, editing, or removing elements?
Methods that cause mutation include Array.prototype.push(), Array.prototype.unshift(), and Array.prototype.splice() for adding; direct index assignment for editing; and Array.prototype.pop(), Array.prototype.shift(), and Array.prototype.splice() for removing.
Which methods can be used to add, edit, or remove array elements without causing mutation?
To avoid mutation, you can use Array.prototype.slice(), Array.prototype.concat(), Array.prototype.map(), Array.prototype.filter(), and the spread syntax.
What is the key principle when writing code that avoids mutation?
The key principle is to return a new reference to the data after the update. This is a common approach in functional programming, ensuring that a new instance of the array is created instead of modifying the original.
How can you add an element at a specific position in an array without mutating it?
You can use the spread syntax combined with slice(). For example, to add 'Ultron' after 'Thanos': const newVillains = [...villains.slice(0, 2), 'Ultron', ...villains.slice(2, villains.length)]; This creates a new array without modifying the original.