A couple of weeks ago, when we talked about
Array.pop, I mentioned that these methods mutate data. That is: they act on the original array, rather than creating a clone of the original array that reflects its new state (more data, in the case of
push, or less data in the case of
pop). This is contrary to how a lot of other Array methods work, like
filter, both of which create entirely new arrays while leaving the original intact. In fact, let's take a look at two quick examples. Here's the first, showing mutated data:
const nums = [0, 1, 2, 3, 4, 5]; nums.push(6); console.log(nums); // 0, 1, 2, 3, 4, 5, 6
And here's the second, showing non-mutated data:
const pastries = ['croissant', 'pain au chocolat', 'cheddar biscuit', 'cherry danish']; const cPastries = pastries.filter(pastry => pastry.charAt(0) === 'c'); console.log(pastries); // croissant, pain au chocolat, cheddar biscuit, cherry danish console.log(cPastries); // croissant, cheddar biscuit, cherry danish
These different types of methods illustrate, in a nutshell, data mutability and immutability.
let str = 'I enjoy pastries.'; str.slice(8, 16); console.log(str); // I enjoy pastries. const excerpt = str.slice(8, 16); console.log(excerpt); // pastries console.log(str); // I enjoy pastries. str = 'I also enjoy eggs and bacon.'; console.log(str); // I also enjoy eggs and bacon.
See how that first
.slice does nothing? That's because it's returning a snippet of the string, but we're not assigning that return value to anything. What it's not doing is slicing up the original string, which we prove by console logging the original right afterwards.
In all cases, though, data immutability can be useful. More and more, I've found myself gravitating toward immutable methods while eschewing ones that mutate data. We'll talk about a few reasons why next week. See you there!
As always, you can download example files for each of these tutorials from the JS Quick Hits github repo.
Enjoying these quick hits? You can get them five days early by subscribing to our weekly newsletter.