Functional Programming with JavaScript — Part 1
Introduction
Recently I’ve been learning React, and came across a good book, “Learning React, 1st Edition” by Eve Porcello and Alex Banks. However, this series has nothing to do with React. Chapter 3 of the book, titled Functional Programming with JavaScript contains probably the best tutorial about functional programming in JavaScript I’ve ever seen, so I want to share my notes, and hopefully it can help someone learning functional programming with JavaScript.
If you have time, I strongly recommend giving that book a try, even just for its 2nd chapter for ES2015, and 3rd chapter, which is what this series of article is based on.
What Is Functional Programming About?
Functional programming is about these things:
- Immutable. We only modify copies of the original data, never on the original data itself.
- Pure. Functions doesn't depend on outside variables or cause side effects. Any data it needs, it gets it from parameters; anything it changes, it returns as return values.
- Declarative. In source code, we reveal what should happen, but hide how it should happen. This makes our program easier to understand and debug.
In this series, I'll show why those are important, and how to achieve them in JavaScript. Don’t worry; they’re not difficult at all from a technical point of view; the more difficult part is probably about challenging your existing way of writing code.
Immutable Objects
A very common mistake we make is that we modify the object/array we work on while we don't intend to. Here are the 2 most common cases.
Case 1: Using Mutating Methods Without Knowing
If you go to MDN's Array documentation page, you'll see all the methods on Array.prototype. If you read through the documentation, you'll find that some methods modify the array itself, while some others don’t.
For example: in the documentation page for Array.prototype.concat(), it says:
This method does not change the existing arrays, but instead returns a new array.
And indeed, you can test this yourself:
However, take Array.prototype.pop() for another example:
The pop() method removes the last element from an array and returns that element. This method changes the length of the array.
So, if you only need to know what the value of the final item is, using pop() is a bad idea, because it actually changes the array. There will be times when you actually want the last item in an array to disappear, but always be extra careful when you use any method that modify the array or object it works on.
Conclusion: when in doubt, always check the documentation before you use a method to find out whether it mutates the array/object you work on.
Case 2: Modify the Array/Object in the Parameters Directly
Here is a very common rookie mistake:
The function, changeRating, does 2 conflicting things:
- It returns a new mug object.
- It also changes the original mug object.
Usually you only want 1 of them: either you simply want to change the property of an outside object, or you want to create a new object while keeping the original one intact. This method doesn't achieve either.
So how do we make sure we only create a new object with new properties, while keeping the original one intact? It's simple:
The Object.assign line does these 3 things:
- Create an empty object,
{}. - Copy all properties in product inside that empty project.
- Replace the existing rate property with the new value.
This time, you'll see that the original object, mug, was left intact, and we get back a new object, newMug, with our designed rating.
Using ES6's arrow function, we can improve on that further:
But that's not the end of it; let's introduce the object spread operator in ES7:
When we do ...mug, the spread operator expand the object, and unpack all the key/value pairs inside mug. We can wrap those properties inside {} and get a new object.
Don't mind the JSFiddle error message in the editor; it can't recognize spread, but it really works. If you want to use spread in an actual editor, but ESLint complains about it, you can add these into your .eslintrc:
{
"parserOptions": {
"ecmaVersion": 6,
"ecmaFeatures": {
"experimentalObjectRestSpread": true
}
}
}We can improve our example by using the object spread operator so no Object.assign is necessary:
You'll soon see the spread operator used widely with objects and arrays in this article, because it is one of the best tools available to use when we want to create new objects/arrays from the properties of the old one.
Get Charlie Guan’s stories in your inbox
Join Medium for free to get updates from this writer.
We just went over a rookie mistake that a lot of novice JavaScript developers make:
- Return a new object.
- Meanwhile, modify the original one.
That mistake happened because we modified the object in the parameter directly for the wrong purpose. To avoid that, we have 2 options:
- Modify the parameter directly, but don't return anything.
- Create a new object from the parameter, modify it, then return it.
Whether you choose Option 1 or 2 depends on what you intend to do. However, when possible, always choose 2. We'll see why eventually.
We used objects as an example, but it also applies to arrays. After all, arrays in JavaScript are just objects with numerical keys with a few subtle differences. Therefore, let's show an example of keeping original arrays intact using spread operator as well.
First off, a wrong way to start:
Now, let's create a new array and modify that one instead.
Pure Functions
The 2nd aspect of functional programming is about creating pure functions only. By definition, a pure function is a function that:
- Only access necessary information through its parameters.
- Always return a value.
- Never cause a side effect.
Here is a very simple example of an impure function:
newColorsWithBlack is an impure function, because:
- It accesses the array,
colors, not through its parameters, but through a variable from an outer scope. This way, the function assumes/depends on the existence ofcolorsarray. - It doesn't return any value.
- It causes a side effect by modifying
colorsarray from another scope.
How can we rewrite the function so it's pure?
In this new form, we can see it's pure because:
- It accesses the array from its parameter.
- It returns a new array.
- It doesn't cause any side effect; you can see the original array wasn't modified.
Pretty easy concept, right? From a technical PoV, this is probably quite trivial. However, you might wonder: why do we even bother introduce this concept? I've used impure functions all over my codebase and things still work!
From my own work experience, using an impure function has many disadvantages. Let's use our newColorsWithBlack function as an example to illustrate:
It makes assumptions about its surrounding environment
- It's hard to factor
newColorsWithBlackout and move it to another scope or file. You might not be able to movecolorswith it if other functions also accesscolors. - It's hard to change the surround environment, because you'll break the function's assumptions. Any change to
colorswill breaknewColorsWithBlack. - It's hard to write unit tests for the function. You'll have to use setups and teardowns to fake the value of
colors.
It Might Introduce Race Condition
If colors is accessed by multiple places of your program, changing it using newColorsWithBlack might cause race condition. Here is another example:
In the previous example, we used setTimeout with a 0.5 second delay to simulate a very slow operation (could happen if your array becomes big; even a 0.01 second delay can throw a race condition). We used onlyKeepFirst3 function's side effect to change the value of colors; then later on, we incorrectly assumed colors is ready, thus we got wrong values.
As your codebase gets bigger, assumptions like "other functions have processed this shared object/array using side effects, so it must contain the correct data now" can often lead to tricky race conditions. Later, we'll see how to use pure functions to pass around modified data as return values instead of mutating shared objects to avoid this issue.
We’ve only used arrays as examples; let's use an object this time just for the sake of completeness. Here is a pure function that accepts and returns an object without side effect:
In reality, it's impossible to write all your functions as pure functions. Sooner or later, you'll have to access variables in an outer scope. For example, let's say you're building an UI; no matter how pure your codebase is, eventually you'll have to do something like document.getElementById() or $('#content'). We should, however, keep those impure functions to a minimum.
Next
That's enough learning for 1 article! Next post, I will talk about some commonly used functions for arrays: filter, map, and reduce, and how you can benefit from using them.






