Professor Xavier's School for Mutant Arrays
Every array method is unique.
Some modify an array and return the resulting length. Some run a function for every value and return undefined. Others don’t modify anything and return a completely new array.
With 34 methods, there’s a lot to memorize (or search for on StackOverflow).
Fortunately, these methods divide pretty cleanly into two categories: mutating and non-mutating.
Mutating vs Non-Mutating
Mutate is a funny word. Let’s use “modify” instead.
Two methods that let you “add values” to an array are push()
and concat()
but they do it in different ways.
items.push(“chan”) modifies the array assigned to items — it’s a mutating method.
items.concat(["chan"])
does not modify the array assigned to items — it’s a non-mutating method. Instead it returns the result as a new array.
React Favors Immutability
Immuta-what-are-bees? 🐝
React favors functions and methods that don’t modify arrays and objects but — istead — return new ones.
So, you’ll see a methods like slice, join, map, filter, reduce, and concat used a lot. And you won’t see much forEach, push, unshift, and splice.
Take it home
List the Array methods you frequently use. Do these methods modify data (mutating) or do they operate on their array instances without modifying the data (non-mutating)?
Check out this tool Matt Sutkowski recommended in our Discord. It’ll help you answer the questions above: doesitmutate.xyz
Also, join us in Discord 😁