Functional Programming with JavaScript — Part 2

Introduction

In the previous section, we went over some concepts of functional programming with JavaScript. One important idea is that we don’t want to mutate original data unless absolutely necessary; instead, we would duplicate the original data and modify the duplicated one. In this 2nd article of the series, let’s look at some smart ways of manipulating arrays. Of course, you’ll see that we stick to immutability and purity:

  1. They are pure functions as well, so they only access necessary information from their parameters, return results, and don’t cause side effects.

Array Transformation

Duplicate an Array

First off, let’s see the easiest way to duplicate an array. Without any transformation, you can simply do this:

const duplicated = […original];

Join

Let’s warm up with a very simple method.

  1. returns a string, delimited by the symbol you passed in.
  2. doesn’t change the original array.

Filter

Next up, a slightly more complicated, but very practical method: you can use Array.prototype.filter on an array to create a new array, with only the items which pass your tests. Again, this method does not mutate the original array:

  1. takes at least 1 parameter.
  2. runs some tests on that parameter.
  3. returns true or false based on the tests.
  1. accepts a predicate as its parameter.
  2. produces a new array by filtering out unwanted items from the old array.
  3. left the old array unchanged.

Map

Map is a commonly used function for array. Here is a simple example of what it does:

  1. returns a new value for every element. In our example, it returns double the amount.
  2. puts the returned value into a new array.

Reduce

The final function we’ll introduce is Array.prototype.reduce. In short, this function gets called on an array, and reduces the array to a single value, while leaving the original array unchanged.

  1. When you do provide one, the provided default value (10) gets assigned as minimum, and the 1st value (22) gets assigned as currentAge.
  1. returns a single value that’s either a primitive value (max, min, etc), or another object or array.
  2. Takes an optional 2nd parameter as its initial value.
  3. Leaves original array intact.

Summary

In this 2nd article of the series, we took a look at commonly used immutable, pure functions to transform array data. We dedicated an entire article to those functions because they are one of the building blocks of functional programming with JavaScript.