Member-only story

Be Careful with Array Mutators

Nicholas Jamieson
3 min readFeb 21, 2019

--

Photo by Corinne Kutz on Unsplash

A while ago, I wrote a linting rule to highlight an error that I’d made on a few occasions. Let’s look at the error — and its variations — and then at the rule that prevents it.

The error

If you are used to working with fluent APIs — perhaps with D3 or lodash — it feels natural to write Array-based code like this:

const developers = employees
.filter(e => e.role === "developer")
.map(e => e.name)
.sort();

Which is fine. There’s no error in that code.

However, in situations in which you don’t need to filter or map, you might write something like this:

const sorted = names.sort();

It feels natural, but there’s a potential error in there. And it’s an error that can effect hard-to-find bugs. It’s also an error that’s easy to overlook in code reviews.

The sort method mutates the array. It sorts the array in place and returns a reference to the array itself. It does not return a sorted copy of the array. So the sorted and names variables both reference the same, sorted array. And it means that — unless the array was already sorted — any code using the names variable will be dealing with an array in which the elements that been rearranged.

--

--

Nicholas Jamieson
Nicholas Jamieson

Written by Nicholas Jamieson

RxJS core team member; front-end developer; mentor; speaker; open-source contributor

No responses yet