Operation: Iteration Obliteration
And also death to side effects.
This certainly achieves the goal of transforming an array but it produces what’s known as side effects. That is to say, the function
transform() reaches outside of its functional scope, to fetch a reference to
arr and then modifies it. What if this file is several hundred lines long (that’s a different post) and an unsuspecting junior dev attempts to use the
arr function? If she doesn’t know that
transform() exists, she may use
arr thinking that the contents are one thing, but have indeed been changed by
A key principle of functional programming is to, as much as possible, prevent side effects such as the one described above. Data goes in, new data comes out. One way to accomplish that would be:
And so, we’ve performed a non-destructive operation which gives us a transformed version of our original data and keeps the original data in tact. We’re done, right? Not quite. We had to add a new variable declaration and then a return statement on a new line. I don’t know about you, but my favorite type of refactoring results in less code, not more. In general, there’s “cruft code” that doesn’t add to the expressiveness of what we’re trying to accomplish. Try this instead:
Need more flexibility on that transform? Use a closure:
Or if you really want to go nuts:
As you can see, even taking tiny steps towards functional JS yields much more expressive code and (more importantly) much more testable code. This is just the beginning, we’ll keep you posted!