Of all the styles of JavaScript you can write, this one probably draws from the deepest well. Functional programming is older than object-oriented programming and even imperative programming. We’re going to take a few drinks from this well, but try to avoid falling in. FP has so much history and theory behind it that we have to set some boundaries.

There is an expression that “farmers don’t want to own all the land, just all the land their land touches.”

Learning functional programming in JavaScript has this same temptation. Here is a list of statements that might hold true for some people, but are not what we’re dealing with in this chapter:

  • To learn functional programming, you need to learn Scheme/Haskell.
  • To do “real” functional programming in JavaScript, you need to compile to JS from PureScript, TypeScript, ClojureScript, or something else.
  • To learn functional programming, you need to learn the lambda calculus.
  • To learn functional programming, you need to learn category theory.
A Confession

An implicit statement in the above is:

Evan needs to write this chapter as a 900-page book from the perspective of a Math/CS dual PhD (which he isn’t).

Sorry to disappoint, but that’s not going to happen in this chapter.

The focus here is entirely on the practical concern we’ve had all along: building confidence through developing and maintaining the interfaces of our code. To that end, we’ll be covering five main topics:

  • The restrictions and benefits of functional programming
  • The basics of FP
  • More basics of FP
  • Burritos
  • Moving from OOP to FP

The Restrictions and Benefits of Functional Programming

Generally speaking, programming within a functional paradigm requires a bit more structure than a typical JavaScript programmer might be used to. With that structure comes certain guarantees and challenges. In this section, we’ll explore some of the basic trade-offs in attempting a functional style.

Restrictions

Here’s a common piece of code that is often trotted out to denigrate programming in a nonfunctional style:

x = 1;
x = x + 1;

That’s it. It might seem pretty innocent, but there are many problems here. Many JavaScript programmers will be fine with this. Some would just be bothered by the first assignment not being preceded by a var to scope it within a function. Other people would want a let to scope at the block level. As we’ve discussed earlier in the book, what we really want here is a const , which would prevent the reassignment on the second line. On a chalkboard in a math class, this would look especially ludicrous.

We covered earlier how reassignment makes programs more complicated to deal with. But reassignment goes a bit deeper than the strictly practical.

If we were thinking of both of these statements as mathematical facts , is x equal to 1 or does x somehow equal 1 and 1 + 1 ? Apparently it depends where you are in the program, right? So we can’t look at these statements as facts about x anymore. We have variable assignments instead of facts (values in functional terms). Values shouldn’t change. When they do, our programs look less like math and more like sequences of instructions.

Okay, so we should be able to solve anyone’s objections like this, right?

const x = 1
const y = x + 1

The second problem, and this might seem strange, is that just by having assignments to begin with, we’ve introduced the concept of time into our program. There is a time before these values exist, and another one after. Yes, our JavaScript programs are steps of execution no matter how we go about it. However, in declarative programming (of which FP is one type), we seek to deemphasize those mechanics, describing what a program should do rather than how it should do it. Moreover, assignments in and of themselves are worthless unless they’re actually applied to a function (including one that just prints the value of the assignment).

Spreadsheets as Declarative Programming

As a simple example of declarative programming, consider a spreadsheet program. Some cells contain data (facts/values). Other cells contain functions to manipulate and use those calculations. Other cells have functions that use the results of executing other functions.

When using a spreadsheet program, we don’t really think about the flow of execution of the program. Are the numbers displayed in the cells before they are used in other calculations? If a number is used in multiple calculations, which calculation is executed first?

By the way, if you want to try out a declarative programming language that’s especially distant from JavaScript, you should look into Prolog.

If worrying about reassignments and even assignments seems really intense, I have bad news, good news, better news, and then some more bad news. The first bit of bad news is that you might find a number of restrictions in a given functional programming language, such as:

  • Variables don’t exist. They may be called values , which are constants.
  • There is no shared global state (without some difficulty). 
  • Assignment itself is more complex. Values tend to come from or go into functions .
  • Functions should always return something.
  • if statements without else branches are invalid.
  • Functions are declared along with a type signature that specifies inputs and outputs .
  • There is a compilation step where types need to line up properly (more on this later).
  • The language makes it difficult to use side effects that may be trivial in other languages .
  • There’s no concept of null . 
Note

You may find that not everything in this list applies to every functional language.

Benefits

The good news is that with those restrictions come a ton of benefits.  When values exist only in a small scope and can’t change, you can trust that a function called with the same arguments always returns the same result. This is also called idempotence , which is half of what makes a pure function .  The other half is not producing side effects.

By this point in the book, functions returning something is a goal we’ve been striving for anyway, but what’s the benefit of restricting else ? If you look at code for an if without an else , you might notice that it will either change the returned value, throw an error, or have some other kind of side effect. In other words, it’s a vector for impurity to sneak into our functions.

Because type signatures (we cover them more later, but just think about how we talked about input and output types like string and number in Chapter 5 ) establish what types of values get passed around where, functional purity can be protected at a compilation stage if you have one (and it’s nice to discover errors, including type errors, then rather than at runtime). In a stricter functional programming language like Haskell, you can have impure functions, but they can be complicated to set up. They could very well take the “ fun ” out of “ fun ctional” for many and make the code just “ctional.”

As far as the last item in the bulleted list in the previous section, as we talked about before, avoiding null saves us a billion dollars.  Of all the restrictions, this is the best. You won’t feel restricted while swimming in your Scrooge McDuck vault of gold.

And now for the better news. The implications of using pure functions range from convenient to quite compelling. In a stateless world, there is no longer a question of when something happened. If two processing cores of a machine (or more) run the same function, they get the same result, and it doesn’t matter which finishes first. In other words, you can avoid race conditions .

Additionally, if functions always return the same thing when called with the same arguments, they are referentially transparent , which means we can substitute the evaluation of the expression with the value produced. Following from that, we (through minor effort in setting up) never have to evaluate a function twice in a row.

By the Way, Recursion

If you’ve read this far into the book, you’re either familiar with recursion or completely capable of understanding it. We haven’t done much with it so far, but it deserves a brief explanation.

If you have a loop, you could likely use recursion instead. For instance, finding an element can be defined iteratively like this:

function find(toFind, array){
  let found = "not found";
  array.forEach((element) => {
    if(element == toFind){
      found = "found";
    };
  });
  return found;
};
console.log(find(3, [3, 9, 2])); // found
console.log(find(3, [2, 9, 3])); // found
console.log(find(3, [2, 9, 2])); // not found

But we could also have a recursive find :

function find(toFind, array){
  if (array[0] === toFind) {
    return "found";
  } else if(array.length === 0){
    return "not found";
  } else{
    return find(toFind, array.slice(1));
  }
};
console.log(find(3, [3, 9, 2])); // found
console.log(find(3, [2, 9, 3])); // found
console.log(find(3, [2, 9, 2])); // not found

Both options have performance implications, which we won’t get into here, and neither is necessarily the best version of find . This is just to illustrate a couple of things you need for recursive functions.

First, you need a call to a function inside of its declaration (e.g., find calls find() inside of itself).  Second, you need a “base case” code path (usually prescribed by a conditional) where the function won’t call itself. In this case, we have two terminal branches where the function returns "found" or "not found" . If you don’t have a base case (or something like a timeout), you will end up with an infinite loop.

Let’s explore the idea of referential transparency with everyone’s favorite recursive function, factorial :

function factorial(number){
  if(number < 2){
    return 1;
  } else {
    return(number * factorial(number - 1));
  }
};
factorial(3); // returns 6

That’s all well and good, but since we have a pure function (the outputs depend only on the input), we have an opportunity to memoize it:

const lookupTable = {};
function memoizedFactorial(number){
  if(number in lookupTable){
    console.log("cached");
    return lookupTable[number];
  }
  else{
    console.log("calculating");
    var reduceValue;
    if(number < 2){
        reduceValue = 1;
    } else {
      reduceValue = number * memoizedFactorial(number - 1);
    }
    lookupTable[number] = reduceValue;
    return reduceValue;
  }
};
console.log(memoizedFactorial(10)); // calculating 10 times
console.log(memoizedFactorial(10)); // cached 1 time
console.log(memoizedFactorial(11)); // calculating (once) and cached

If we run this example, we’ll see that any time we calculate a value, we add it (along with the number parameter) to the lookup table. The first call, memoizedFactorial(10) , has to do a bit of work. The second call only needs to reference the lookup table. The third call still has to calculate for 11 , but 10 is already a solved problem, so it just pulls that from the lookupTable .

But now our function relies on something other than explicit parameters! It has become impure! How can we avoid this? We need to make the lookupTable an explicit parameter:

function memoizedFactorial(number, lookupTable = {}){
  if(number in lookupTable){
    console.log("cached");
    return lookupTable[number];
  }
  else{
    console.log("calculating");
    var reduceValue;
    if(number < 2){
      reduceValue = 1;
    } else {
      reduceValue = 
        number * (memoizedFactorial(number - 1, lookupTable))['result'];
    };
    lookupTable[number] = reduceValue;
    return {result: reduceValue, lookupTable: lookupTable};
  }
};
console.log(memoizedFactorial(10)['result']);
console.log(memoizedFactorial(10)['result']);

If you run this, you’ll notice that the cache misses on the second call. This shouldn’t be too surprising when you look at what we’re calling. We have a default explicit parameter for lookupTable that is an empty object, and we never actually pass it in. No cache means no cache hits.

If we add the following code, we’ll see the cache is activated for the second call:

const lookup = memoizedFactorial(10)['lookupTable'];
console.log(memoizedFactorial(10, lookup));

There are other ways we could wrap memoization in using functions. Some memoization functions are made to wrap arbitrary functions, but we won’t get into that here. In any case, memoization is a useful tool for some situations, but the setup does have some overhead.  

The Future (Maybe) of Functional Programming

Let’s get back to some more bad news about FP. Some functional concepts are difficult, and yet, in the long term, the functional people are probably right. Of all the committees, frameworks, and paradigms influencing JavaScript, the functional ideas are showing a lot of promise, because not only are they based on practical software quality principles, but they are also a lens into the state of hardware today and in the future: memory is cheap and computers are parallelizing with multiple cores to keep up with Moore’s law. But in order to make use of hardware with multiple processors (or distributed systems), we need code that doesn’t care about order of execution so that it can execute in parallel.

It’s not hard to see how performance is beginning to become a quality concern. I don’t have a crystal ball here, but “You’re not writing referentially transparent, pure, functional, concurrent code with compile-time type checking?” becoming the new “You don’t write unit tests?” doesn’t seem too far-fetched.

The best news, however, is that throughout the earlier parts of this book, we have already made significant efforts toward many of the good parts of functional programming. Not reassigning variables is definitely something we’ve been through. Keeping variables scoped tightly and converting between functions and variables are both things we’re pretty handy with at this point too. And not every other aspect is terribly difficult. For example, separating pure and impure functions is not too hard if we’re already good at extracting functions.

The Basics

In JavaScript, the benefits and restrictions of programming in functional style are not as simple as a switch that can be flipped on and off. This is partly because functional style is not rigorously enforced in JavaScript, and also because at a basic level, many of the restrictions we can adhere to and the benefits we can enjoy look generically like “better code” rather than “steps toward functional programming.” Let’s look at a few of those now.

Avoiding Destructive Actions, Mutation, and Reassignment

When we see a reassignment, we should seek better solutions. For the following trivial example, we would just use const x = 2 . A preference of const to let also speaks to this intention:

let x = 1;
x = x + 1;

Avoiding reassignment in conditional tests

Reassignment comes up a lot in conditionals too. Instead of this form:

function func(x){
  if(x >= 2){
    x = x + 7;
  }
  return x;
};

we can do this:

function func(x){
  if(x >= 2){
    return x + 7;
  } else {
    return x;
  }
};

// or

function func(x){
  return x >= 2 ? x + 7 : x;
};

You might also see (re)assignments in the conditionals themselves:

function func(x){
  if((x = x + 7) >= 9){
    return x;
  } else {
    return x;
  }
};

This is a tough one. Reassignment is bad enough, but in conditionals, any assignment can make things a bit more confusing. Not only that, but our else branch returns the original value of x plus seven. In other words, both code paths are the same. Was that obvious to you? Maybe it was, but for me, it took a minute to realize. Anyway, let’s assume that we have tests in place, and our else branch does execute how we want it to.

Where do we go from here? We can start to deal with this by not changing the value of x :

function func(x){
  if((x + 7) >= 9){
    return x + 7;
  } else {
    return x + 7;
  }
};

So now we have repetition, which is ugly, but would be especially bad if instead of + 7 , we had some more expensive call that we had to execute twice. However, we have made something else clear by being explicit with the conditionals. We’re returning the same thing regardless of input (assuming x is a number), so our function can become this:

function func(x){
  return x + 7;
};

Did you immediately see this when we had the reassignment in the conditional? If so, awesome. Not everyone will see that clearly, though.

Here’s another case that is even worse to deal with:

function func(x, y){
  if (x > 1000){
    return x;
  } else if((x = x + 7) >= 9){
    return x;
  } else {
    return y;
  }
};

This one is tricky, but let’s first remove the reassignment:

function func2(x, y){
  if (x > 1000){
    return x;
  } else if((x + 7) >= 9){
    return x + 7;
  } else {
    return y;
  }
};

This has three effects. First, our else if case’s return is complicated. Second, we’re now doing the + 7 operation twice. That’s not a big deal here, but if the calculation was more expensive, we would expect to take a performance hit. Third, the else case has the original value of x as it was passed in. Even though we’re not using it, it’s good to be aware of that.

To avoid running the function twice, we could set a newX variable immediately:

function func3(x, y){
  const newX = x + 7;
  if (x > 1000){
    return x;
  } else if(newX >= 9){
    return newX;
  } else {
    return y;
  }
};

This prevents us having to execute the + 7 operation twice, but now we’re doing it once, even when the if branch is the one we’re executing (which doesn’t need newX or x ). One way of handling this is by introducing a nested if statement:

function func4(x, y){
  if (x > 1000){
    return x;
  } else {
    const newX = x + 7;
    if(newX >= 9){
      return newX;
    } else {
      return y;
    }
  }
};

Now we have three code paths, but we’re only doing the x + 7 operation once. Even with the extra complexity, you might find this clearer than burying an assignment inside of a conditional. By the way, in a more complex/expensive operation than + 7 , instead of our const we might prefer a memoized function, like this:

function func5(x, y){
  if (x > 1000){
    return x;
  } else {
    if(memoizedAddSeven(x) >= 9){
      return memoizedAddSeven(x);
    } else {
      return y;
    }
  }
};

So we could have a cache-aware function instead of a cache variable . This would also let us revert to our simpler form:

function func6(x, y){
  if (x > 1000){
    return x;
  } else if (memoizedAddSeven(x) >= 9){
    return memoizedAddSeven(x);
  } else {
    return y;
  }
};

Of course, all of what we’ve done so far has been fairly mechanical. If we actually understand the code, another refactoring would save us from having to mess around with caching variables/functions and ensure we take the performance hit (albeit a very, very small one for addition in this case) only once:

function func7(x, y){
  if (x > 1000){
    return x;
  } else if (x >= 2){
    return x + 7;
  } else {
    return y;
  }
};

This change might have been obvious from the start, but refactorings that avoid actually understanding the code are easier to apply in many cases. All that said, odds are if we ended up with a function like this, there’s some deeper problem elsewhere in the code. (By the way, in this form, we still have three magic numbers, and our names for parameters and the function are not descriptive, searchable, or unique.)

How Overrated Is Understanding Code?

It might sound like heresy, but hear me out.

It’s completely possible to refactor (with tests in place, of course) without having a good understanding of what the code actually does. “Digging in” (especially while debugging) is a tremendously important skill, but quality improvements through refactoring do not always demand it. As in our last example, you may hit a point where without having further context, you’re stuck, but this is not always the case.

Similarly, when you have a failed test build (or a bad deployment, eek), it’s tempting to “dig in” and see what exactly went wrong, but sometimes, it’s much faster to just go back to a version of the code that behaved properly and work from there.

Understanding the code (which includes tracing the execution path, and examining variables and other state at various points in time) is useful but can be tedious. It’s important to recognize that it’s not the only strategy that works.

Avoiding reassignment in loops

Next, let’s talk about loops (which frequently have a “loop counter” variable that updates). Instead of using them, we should prefer using forEach , at minimum:

[3, 4, 2].forEach((element) => console.log(element));

This is fine for when we have a simple side effect we want to run, but rather than using a loop (or forEach ) to change values inside of an array, we can use map to create a new array with new values:

[3, 4, 2].map((element) => element * 2);

When we want to filter an array to kick some elements out, we can use filter , rather than creating a new array and pushing on the elements that are okay:

[3, 4, 2].filter((element) => (element % 2 == 0));

When we need to transform an array into some other type of value (object, number, etc.), we’re likely going to want reduce :

[3, 4, 2].reduce((element, accumulator) => element + accumulator);

In a for loop, any of these functions would tend to work with the index of the loop, as well as an outer variable that reassigns to itself over time. An atomic creation of a new variable makes tests easier and keeps values the same.

If you’re   looking for a good jumping-off point for higher-order functions like these, the Array docs are a good place to start.

But You Can Do Anything with a for Loop!

Yes, you can. You can loop through all of your values and build up some other value. You can implement all these with a for loop or forEach :

  • every
  • filter
  • find
  • forEach (itself)
  • map
  • reduce / reduceRight
  • some

You could also implement them all with reduce , but why would you do either? Use the right tool for the right job. map gives you a new array of transformed elements. every , filter ,  find , and some return something based on a test conditional you provide .

reduce gives you some new value based on your array. It’s a bit harder to use than the others, but if you want to get back some accumulated value—a sum/product/object/string/array (that won’t work with map )— reduce is what you want. For an easy test of what you want, look above where your loop starts. If it’s not the same type as what you’re looping through (a number or an empty object usually), you probably want to use reduce .

Using these functions means using functions that take functions as parameters. It might not seem exotic at this point in the book, but it’s a good entry point toward exploiting JavaScript’s support for first-class functions (functions as input and output to other functions). Some may argue that that’s not “real” functional programming, but will still admit that we’re moving closer to a declarative style in contrast to an imperative style. Think of this as telling the computer what to do, instead of how to do it.

Avoiding reassignment in conditional bodies

Although we generally have tried to reduce if statements (through polymorphism of subclasses, or through delegation to properties, or extracting them to their own named function as a first step), there are places where they will show up in your code. When that happens, try to provide an else case and new variables. So instead of this:

let emailSubject = "Hi";
if(weKnowName){
  emailSubject = emailSubject + " " + name;
};
sendEmail(emailSubject, emailBody);

try to do this:

if(weKnowName){
  let emailSubject = `Hi ${name}`;
} else {
  let emailSubject = "Hi";
};
sendEmail(emailSubject, emailBody);

This is much more flexible, as we perceive a few transformations:

function emailSubject(){
  if(weKnowName){
    let subject = `Hi ${name}`;
  } else {
    let subject = "Hi";
  };
  return subject;
}; 
sendEmail(emailSubject(), emailBody);

Then it is clear that we don’t need the assignment at all:

function emailSubject(){
  if(weKnowName){
    return `Hi ${name}`;
  } else {
    return "Hi";
  };
};
sendEmail(emailSubject(), emailBody);

Now, we can simplify the statement with ternary syntax:

function emailSubject(){
  return weKnowName ? `Hi ${name}` : "Hi"
};
sendEmail(emailSubject(), emailBody);

Avoiding destructive functions

Another source of mutating values is through using “destructive” functions.

Let’s look at splice first:

const x = [1, 2, 3, 4];
x.splice(1);

splice (with one argument) will start at the index of that argument (the second element in this case) and return the rest of the array. But it also updates your array, leaving you with [1] . And because this isn’t a reassignment, const doesn’t save you from splice ’s destruction.

Instead of splice , slice will behave itself:

const z = [1, 2, 3, 4];
z.slice(1);

This returns [2, 3, 4] also, but doesn’t clobber the original z array.

Arrays have destructive functions, including fill , push , and pop . Object has defineProperties . Numbers and strings as variables have + and = to, respectively, add and concatenate. Arrays have functions (and syntactic sugar, e.g., x[0] = "something" ) to alter values at particular indices. Objects have Object.assign , which mutates the  first argument object you give it (you can avoid this by giving it a {} as the first argument), as well as dot ( .prop = ) and bracket ( [prop] = ) syntax to alter or create properties.

It might seem crazy to avoid direct assignment and a good number of functions just because they are destructive. But you might find it’s easier to work with this discipline than to track down a few (or many) rogue global variables that mutate throughout thousands of lines of code.

Avoiding destruction in general

Not all functions and convenience syntaxes (such as = ) come with a safe version, and const doesn’t protect you from mutations (only assignments). So if you want to avoid variables varying , create new variables to pass along. If you want to reassign something, odds are you’re wanting its updated value , not just a copy, right? It might as well be a new variable with a new name.

As far as destructive actions (and yes, this includes reassignment and even just assignment when the scope is too large), avoid not only using them (when possible), but also creating functions that are destructive. It is somewhere between odd and worrisome that “global variables are evil” is seen as common knowledge, but “reassigning variables” doesn’t share that reputation, even though they are two sides of the same coin.

Databases are a giant global variable

For some reason, most people give databases a free pass as far as global variables go, although there are some promising approaches that treat each moment in time as a distinct “value” for the entire database. Time will tell if those systems become common wisdom at some point.

Not everyone considers the same things “destructive.” For some people, assignments are fine. For other people, reassigning is fine (ugh). For other people, adding or changing the contents of an array or object is fine. For some people, it’s an issue of scoping. Even if loop counter variables are unnecessary noise (and we can at least use forEach or other iterable comprehensions instead), some people are fine with variables that update within a loop. Others are fine with reassignments if the variable is only scoped to the function.

An Awesome Indicator of Destruction

Ruby has a convention (taken from Scheme) to indicate destructive functions with a ! after the function name (also, ? is appended for functions that return a boolean). Although it’s not used with terrific consistency, it’s a very good idea.

Unfortunately, we don’t have that convention, and the interpreters don’t allow for it anyway. But given that it is a convention in Ruby that is so widely ignored, its greatest value might be your realization that you (should you happen to be working on Ruby code) have a capacity to care about something that others seem not to. That’s not the same as “mastery” or “intelligence,” and certainly not something to berate someone about. But it might be helpful to see which library authors care and don’t care about these ideas.

Interestingly enough, ! and ? are used for completely different purposes in the Swift programming language.

For this chapter, we’re taking a deliberate, hard line and saying destructive actions are not okay. If you really want to avoid state, and have all of the nice things (idempotent, pure functions that can be tested, cached, and parallelized easily), this is the price of admission. It might seem like an expensive ticket,  but if your choice is between this and a compiles-to-JS language, this approach is easier. Definitely try out a functional compiles-to-JS or standalone functional language at some point, though, if you’re interested in going from self-discipline to compiler-enforced discipline.  

Don’t return null

Let’s look at some code from the last section:

function emailSubject(){
  return weKnowName ? `Hi ${name}` : "Hi"
};
sendEmail(emailSubject(), emailBody);

If someName and nullName were both objects with a defined toHi function, we could write this as:

const someName = {
  value: "some name",
  toHi(){return `Hi ${this.value}`};
};
const nullName = {
  value: "",
  toHi(){return "Hi"};
};
// assuming getName will get someName or nullName
sendEmail(getName().toHi(), emailBody);

For further cleanup, in Chapter 9 we discussed how we might wrap an object with a null object. We’ll cover a similar but better (albeit initially somewhat esoteric) idea later in this chapter called Maybe , and its friend Either .

Referential Transparency and Avoiding State

Can data always be the result of a function call? Yes, but any functions relying on or manipulating nonlocal inputs (free variables) cannot be replaced by their return value without extra consideration. As we briefly covered earlier in this chapter, the ability to replace a function call with its return value (without changing the program’s behavior) is called referential transparency .

As an example, emailBody in the last section could instead have been a call to an emailBody() function, right?

What about this?

x = 5;

That could be:

function five(){ return 5 };
five();

Or we could just call it right away:

(() => 5 )()

Or we could return what we pass in instead:

((x) => x)(5)

We can do a similar transformation for functions that actually calculate things. For example, this:

3 + 5

could be:

(() => 3)() + (() => 5)();

The first function returns 3 . The second returns 5 . Then they’re added. Here a 3 is passed into the first function, which is returned. A 5 is passed into the second function, which is returned. Then the results of those are calculated:

((x) => x)(3) + ((y) => y)(5);

If we combine the two expressions, we get this:

((x, y) => x + y)(3, 5);

This might look odd, but it has a few features worth noting. First, the arguments we passed in are scoped only inside of this line. Second, this anonymous IFFE is starting to look a bit like Lisp with a few extra bits of syntax. Third, if we assign to what is returned here, we are assigning a numerical value:

const result = ((x, y) => x + y)(3, 5);

result is 8 , the number. It’s not a function. It’s the result of a function call. If we’re living in a stateless, side effect–free world (although it’s also guaranteed by us using only explicit inputs), that means that we can replace any of the previous calculations that return 8 with just an 8 . And that means that we can replace any instances of result with 8 . We never have to do this calculation again with these parameters.

This is referential transparency in action.

Why should the parameters change anyway? Well, let’s say we have this situation:

const recentLogins = ((x, y) => x + y)(db.loginsToday, 
                                       db.loginsYesterday);

Now we’re looking to the outside world to provide us with values that update in the database. We have a huge ball of state called a database. We don’t have to use a database as a place to put lots and lots of variables. Just like in our program, we could be creating new values, rather than updating them:

const today = // some specific date
const yesterday = // some specific date
const recentLogins = ((x, y) => x + y)(db.logins(today),
                                       db.logins(yesterday));

Disk storage is incredibly cheap, and lookups shouldn’t be too bad if you can index by time in your database (especially given that you should only have to do the lookup once!). Additionally, if you’re not overwriting (aka updating, aka throwing away) database information, you should be able to play back the state of your application given a particular query (this also assumes being able to retrieve the version of the code at the same time).

Aren’t We Just Hardcoding Variables? What About My Dynamism?

Whenever we introduce a state change, we’re creating a concept of time as well. There’s a world before the state change, and a world after. Once you destroy information, it’s much harder to consider what might have gone wrong or restore to a previous state.

Additionally, in high-traffic websites, real-time queries and page loads are optimized for the speed of interface availability, 1 not the speed of the delivery of every new version of every piece of information in the database. That’s why caching exists. Trade-offs are made between delivering something that is fast enough, and something that is recent enough. We’re not going to get into making recentLogins cache-aware, but the point is that by parameterizing the calls to logins and setting our database up with time in mind, we’ve giving recentLogins the opportunity to be cached by virtue of it being referentially transparent (for a certain time period). In reality, we’d probably want this to run more than once a day, but letting this (or something much more complex) block showing someone something (even if it’s a little stale) would not make for a good experience.

We got a little off track there, but the main point is that nothing has to be in a variable (other than the global defaults) for a program to work. Instead of creating objects, we can have functions that store values. Our entire program could be functions wrapping other functions, all kicked off by a single parameter to start the data flowing.

Our program could look a lot like Lisp. Our program could look a lot like XML with parentheses. This is the central concept in Lisp, by the way. The abstract syntax tree (AST) to describe how the program works is, in most languages, in a somewhat different form than the source code. In Lisp, it’s the same. This is called homoiconicity .

JavaScript does not share this feature with Lisp, but you can get far closer with some coding styles than others. In any case, there is clearly some link between state, interface, functional programming, and lots of parentheses. The main point of this section is that we have a lot of options and flexibility when it comes to how data enters and is used by our program, and these variations matter beyond syntax.

Handling Randomness

In Chapter 4 , we dealt with randomness mostly by avoiding thinking about or testing it. We’re not going to go too in-depth here either, but in the context of functional programming, we need to address that randomness makes our functions impure (meaning we cannot rely on them to yield the same output when given the same explicit input). In JavaScript, we call Math.random and we get a “random” value. But what we’re actually getting is a “pseudorandom” number, which is calculated based on some “seed” value, usually having something to do with time. Unfortunately, this seed value cannot be set in our native Math.random function.

If it could be set with a seed, we could generate the same “random” value sequence. For instance, it could work like this (but not in native JavaScript):

const mySeed = 3;
let rng = setRng(myseed);
rng.gimmeRandom();
// returns 2593
rng.gimmeRandom();
// returns 8945

rng = setRng(myseed);
rng.gimmeRandom();
// returns 2593
rng.gimmeRandom();
// returns 8945

That means that even functions that appear random are actually deterministic. This is handy, because you can have random-like numbers that you can test against. It is possible that for your application (or just your tests), this kind of randomness is enough.

Keeping the Impure at Bay

There are three functions in here (not including tests). Can you pick out the impure ones?

const test = require('tape');
const testdouble = require('testdouble');
var x;

function add(addend1, addend2){
  return addend1 + addend2;
};

function setGlobalFromAddition(addend1, addend2){
  x = add(addend1, addend2);
}

function readAddition(addend1, addend2, done){
  console.log(add(addend1, addend2));
  done();
}

test('addition', (assert) => {
  assert.equal(add(2, 3), 5);
  assert.end();
});

test('setting global', (assert) => {
  setGlobalFromAddition(2, 3);
  assert.equal(x, 5);
  assert.end();
});

test('setting global again', (assert) => {
  setGlobalFromAddition(2, 8);
  assert.equal(x, 10);
  assert.end();
});

test('calling console', (assert) => {
  testdouble.replace(console, 'log');
  readAddition(2, 3, () => {
    testdouble.verify(console.log(5));
    assert.pass();
    testdouble.reset();
    assert.end();
  });
});

addition is pure because it relies only on its inputs, and returns an output without having any side effects. It is also completely trivial to test. Good job, addition .

As for the other two functions, we decided to test them even though they’re impure. setGlobalFromAddition seems easy enough to test. The second and third tests run fine. But what if instead of a “dreaded evil global variable,” this was a value in a database? And what if other people were testing their code using the same database? Obviously, we should expect occasional failures if we’re depending on global shared state and all trying to use the same datastore, right? More realistically, whether it’s global state in code or a database, if the number of tests we need to run is large enough, we’re going to want to parallelize our test suite. And then, we will see failures. Impure functions rely on something other than their explicit inputs, and that includes not just nonlocal variables (and functions if they themselves are impure), but also databases and the implicit this argument (if it is not immutable). That last point bears repeating, as it is a pretty big shift from how object-oriented programming tends to work: in functional style, we should prefer using explicit inputs and outputs to accessing and modifying a this value.

All in all, functions like setGlobalFromAddition will make our testing more difficult. Maybe not immediately, but even without a more complex program that mutates x in multiple places, we already can see tests that cannot be trusted to run in parallel.

The third function, readAddition , makes a call to console.log , so it is an impure function with a side effect in it. The complexities of testing this were explored in the previous chapter, but in the context of this chapter we have another reason, beyond the mechanics of testing, for why working with this is inconvenient: I/O calls are side effects and make impure functions. Impure functions are hard to test.

If you like, you could try namespacing your impure functions (don’t forget to namespace the function calls as well). A simple object would work:

const impure = {
  setGlobalFromAddition(addend1, addend2){
    x = add(addend1, addend2);
  },
  readAddition(addend1, addend2, done){
    console.log(add(addend1, addend2));
    done();
  }
};

If you find doing this separation annoying, you really wouldn’t like the machinations you have to do to mix pure and impure code in some functional languages (like Haskell ).

Hopefully, this section has made three things clear. First, it is easy to tell pure from impure functions. If you know that something will always run the same way, with the same input, and not produce a side effect (meaning anything that doesn’t simply return a value), then it is pure. Second, impure functions are harder to test. Third, the simpler (in terms of bulk, inputs, and outputs) your functions are, the better chance they have at being pure.

At this point, we’ve talked over some of the basic hygienic processes you can enact in your code to make it more functional, and also discussed some of the benefits of doing so, including purity, referential transparency, and easier testing. The approaches we’ve taken and our goals for the code are not unlike those found in the rest of the book. We’ve already covered a preference for less bulky functions with few inputs and one clear return value. We’ve also covered why array comprehensions make more sense than for loops. Reassigning variables has been discouraged plenty of times earlier.

Now that we have a new perspective on some of our earlier concepts, it’s time to branch out. Next we’ll be looking at some features that can give us more functional interfaces. 

Advanced Basics

In this section, we’ll be exploring some fundamental aspects of functional programming that are still foreign to many JavaScript programmers:

  • Currying
  • Partial application
  • Function composition
  • Types

What you can’t get from just plain JavaScript

Having a compilation step and a type safety system in place (which JavaScript doesn’t) is actually pretty handy. Using a compiles-to-JS language like TypeScript or Flow will help you realize some of those benefits. Alternatively, you could just go straight for Haskell, Clojure, or Scala.

Currying and Partial Application (with Ramda)

One functional concept that you can exploit to make your code more flexible is using currying and partial application. Before explaining those terms in the text, let’s look at a bit of code:

function add(numberOne, numberTwo){
  return numberOne + numberTwo;
};
add(1, 2);
// 3

This is our favorite addition function so far. It works beautifully. But some (FP rapscallions ) would have you believe that this one is better:

function add(numberOne, numberTwo){
  return function(numberOne){
    numberOne + numberTwo;
  };
};

There is some weirdness here:

console.log(add(1, 2));
// [Function]

Did we break our perfectly good addition function? Yes.

Now it just makes a function that doesn’t care about that second argument ( 2 ) at all. Or does it?

We can still use add like this:

console.log(add(1)(2));
// 3

We just replace the , with )( , and then we’re good. But that doesn’t explain how it works or why we’d want to do that.

Well, the first thing to notice in our second addition function is that it returns a function. That means that when you run add(1) , you get back a function that is waiting for the 2 (or something else):

const incrementer = add(1);
incrementer(2);
// 3

Our incrementer is a partially applied function. We took our original function that took two arguments, and partially applied one argument that it needed, creating a new function with reduced arity (the number of arguments something takes; e.g., a function with an arity of 1 takes one argument).

Currying is not the same thing as partial application. This was the partial application part:

const incrementer = add(1);

We happened to assign it to a variable, but the partial application was when we did this: add(1) . Currying is what we did when we transformed our normal two-parameter function (i.e., a binary function) into one that took one argument (i.e., a unary function). What we didn’t do, however, was use a curry function to do that. We curried it manually. As of right now, we don’t have a way to take any function of any arbitrary arity and curry it.

For that, we need Ramda. The underscore and lodash libraries do similar things, but Ramda has the coolest name and graphic. Also, underscore doesn’t have the curry function. Comparing and contrasting the libraries is an exercise left to the reader, so let’s continue by installing Ramda:

npm install ramda

Next, let’s try it out:

R = require('ramda');

function add(numberOne, numberTwo){
  return numberOne + numberTwo;
};

const curriedAdd = R.curry(add);

console.log(curriedAdd(1));
console.log(curriedAdd(1)(2));
console.log(curriedAdd(1, 2));

It’s pretty easy to use. We just require it and write our binary function as we normally would, and then R.curry does some magic to it:

[Function]
3
3

Our output is better than expected. Where our normal (uncurried) function would choke on the first one (giving us NaN by adding 1 to undefined ), this gives us a partially applied function. Supplying (1)(2) as arguments gives us 3 , just like we got from our manual currying process. As a bonus, the curried function still works with our original arity of 2. Passing two arguments with (1, 2) still works fine!

Also, the following works as expected:

const increment = curriedAdd(1);
console.log(increment(3));

How would we have built increment if it wasn’t curried? Maybe like this?

function increment(addend){
  return add(addend, 1);
};
console.log(increment(3));

It’s only two more lines in this case, but what if we had increment , addFive , addTen , and so on? Or what if the implementation were more complex?

In case you’re not quite on board with currying, here’s another possibility. You know that map function we’ve been praising throughout the book? What if I told you it wasn’t that awesome?

Here’s something that works okay:

const square = (thing) => thing * thing;

console.log([2, 4, 5].map(square));

But what if you want to reuse a mapSquares function? Our data is stuck in front of the dot (.) , so what should we do? Altering Array.prototype is strictly a no-no. We could create a new class that extends Array , alter that prototype, and make our [2, 4, 5] an instance of that subclass.

Or we could let Ramda do some work:

R = require('ramda');
const square = (thing) => thing * thing;

const mapSquares = R.map(square);
console.log(mapSquares([2, 4, 5]));

console.log(R.map(square, [2, 4, 5]));

Ramda’s map function is already curried, so we can partially apply square to make mapSquares , later applying the data. But it also allows for a convenient, two-argument version if we feel like “fully applying” the function all at once.

That’s only two of Ramda’s functions ( curry and map ), and we’re already seeing more flexible, reusable, and shorter interfaces.

What About this?!

Isn’t this the most important keyword in JavaScript? And now, Ramda is just throwing it away? Without a doubt, this generates more confusion, questions, and blog posts than nearly any other topic, with the possible exceptions of “Prototypes are good/bad” and “What library should I use for X?”

But that’s not the same as being “important.” If we can get this kind of flexibility and clarity, then this is our sacrifice. Not only is determining what this is a bit confusing, but it also ties up what could be explicit arguments. Ramda just acts like a namespace, which is closer to how “real” functional programming works.

I might even go as far as saying that using this makes your functions “impure.” If you don’t want to, that’s okay, but isn’t the this context just shared mutable state?

Function Composition

Okay, so we saw that Ramda was pretty awesome, but you might be thinking that lodash and underscore will work just as well for composing functions.

Let’s give that a shot with the last example (after you run npm install lodash ):

_ = require('lodash');
const square = (thing) => thing * thing;

const mapSquares = _.map(square);
console.log(mapSquares([2, 4, 5]));
console.log(_.map(square, [2, 4, 5]));

Kaboom:

TypeError: mapSquares is not a function

We can still do this just fine:

console.log(_.map([2, 4, 5], square));

It works, but wait a second...that’s backward!

Yes, it is—and traditional. And that tradition of putting data before the callback is an impedance to composing functions. We can fix it:

function mapSquares(data){
  return _.map(data, function(toSquare){
    return toSquare * toSquare;
  });
}
console.log(mapSquares([2, 4, 5]));

Admittedly, we can refactor to:

function mapSquares(data){
  return _.map(data, square);
};

And to:

const mapSquares = (data) => _.map(data, square);

But ugh...before, we got away with just this:

const mapSquares = R.map(square);
Point-Free Programming

In this chapter, we’re aiming for “point-free” style most of the time. That means not working directly with your inputs. You can apply functions to them, but if you give the input a name (like data ) and work with it directly, you’ve created a point . The word “point” is related to topology, and not the dot ( . ) in JavaScript.

In the preceding example of mapSquares , this one is “pointed”:

const mapSquares = (data) => _.map(data, square);

And this is point-free:

const mapSquares = R.map(square);

It’s difficult (maybe impossible) to make all of your functions point-free, but attempting to do so should help shorten a lot of your function definitions.

It’s worth noting, however, that not everything will be easy.

Earlier, we had this bit of code:

[3, 4, 2].forEach((element) => console.log(element));

It might look like we could just do this instead:

[3, 4, 2].forEach(console.log);

But this is actually different. Although we only want to print the number, we’ll end up printing:

3 0 [ 3, 4, 2 ]
4 1 [ 3, 4, 2 ]
2 2 [ 3, 4, 2 ]

That’s the number, the index, and the full array. forEach will supply three parameters to a callback function if it wants them. console.log will happily print as many arguments as it is passed, but we can make a new function based on log that only uses its first argument:

const logFirst = (first) => console.log(first);
[3, 4, 2].forEach(logFirst);

This topic goes pretty deep. There are functions to turn any function into a unary function (as we did here), as well as functions of another arity. You can reorder parameters as they come in, and create functions that are partially applied with placeholder arguments in arbitrary positions in the function signature.

The bottom line is, if you do a lot of function composition and strive for point-free, odds are that you’ll end up fiddling with your parameters a bit.

Hopefully, everyone will get together and decide that data first is a problem. But in the meantime, it’s just one level of working with data directly when we have the wrong argument order, right? At first, yes. But as with conditionals, null returns, and every kind of bulk in the code, complexity seems to breed when no one’s watching. More practically, you’ll see more nesting (and data variables) if you compose your functions with a data-first library.

As you add functionality, you’ll either be making your code more complex (in the function calls or the function definitions) or composing new functions. Let’s see that in action. If we wanted to raise everything to the fourth power, we could complicate the function call and be done:

R = require('ramda');
console.log(R.map(square, R.map(square, [2, 4, 5])));

Or we could do something like this:

function fourthPower(thing){
  return square(thing) * square(thing);
};
console.log(R.map(fourthPower, [2, 4, 5]));

But Ramda has another trick up its sleeve, called compose . Check this out:

const fourthPower = R.compose(square, square);
console.log(R.map(fourthPower, [2, 4, 5]));

And we could combine that with map into a new mapFourthPower as well:

const mapFourthPower = R.map(fourthPower);
console.log(mapFourthPower([2, 4, 5]));

And yes, we could actually compose with console.log too (if we wanted to log the elements, rather than the array):

const printFourthPower = R.compose(console.log, square, square);
R.map(printFourthPower, [2, 4, 5]);

// or because map is curried, this works too
R.map(printFourthPower) ([2, 4, 5]);

So we can choose tiny function definitions and tiny function calls. At worst, we might end up with a few extra function calls around. Although it might be tempting to just have one long chain of compose and map calls, debugging those can be tough. Ramda helps make functions very easy to create and compose. Even though it’s easy to chain things together too, it’s worth striking a balance of how complex your composed functions should be. Smaller composition functions (just like any smaller function) are easier to test and reuse.

memoize revisited with Ramda

By the way, this is what a memoized factorial function looks like in Ramda:

var factorial = 
  R.memoize(n => R.product(R.range(1, n + 1)));

Apologies if you spent much time trying to learn the long version.

Another function you’ll see from time to time is called pipe . It works like this:

var factorial = R.memoize(n => R.product(R.range(1, n + 1)));
var printFact = R.compose(console.log, factorial);
printFact(3);

// is the same as

var factorial = R.memoize(n => R.product(R.range(1, n + 1)));
var printFactPipe = R.pipe(factorial, console.log);
printFactPipe(3);

All in all, Ramda is great, and it exposes the types of functions that make certain interfaces very simple. If you look at the docs , however, you might be surprised at a few things. One is how gigantic it and other functional libraries are. A facade ( Chapter 9 ) extracted for beginners would be nice. 

Types: The Bare Minimum

Before we get to types, one thing that might seem scary about functional code is that if you don’t extract any functions, you could write something like this to accomplish the same work we did in the previous chapter:

console.log(R.map((thing) => 
  thing * thing, R.map((thing) => 
    thing * thing, [2, 4, 5])));

And Ramda or not, we’ve recreated another callback hell (with an unfortunate reuse of a bad variable name and two traversals of the array to boot).

Fortunately, we know how to extract functions, whether we’re doing FP, OOP, or plain old imperative coding. Extracting functions (maybe after decent naming) is our first line of defense against confusing and untestable code.

The case for types

Functional programming has another defense against confusing code: types. When you pass functions to other functions, and sometimes they return the execution of that function and other times they return a function literal, things can get confusing. If you were writing Haskell, you’d deal with this confusion up front. Unlike JavaScript, Haskell actually cares what arity and types you call functions (or compose them) with. So if you try to compose two functions where one would pass a string to the other, which expects a number for input, you’d get a compilation (type) error. The same goes if you try to do something else weird, like this:

console.log(Math.random("beaver"));
// returns 0.21801069199039524 (at least this time, apparently)

Why didn’t this raise an error? It was almost as if an occult hand threw away that argument. This is fine in JavaScript. It’s normal. No compilation means no compilation error. And there’s no runtime error either, because JavaScript functions just don’t care what you give them, unless their function bodies have some opinion.

The inconsistencies in basic operations of JavaScript are well documented, and opinions vary on whether all of the weirdness is a comedy or a tragedy. The reliance on either third-party specs or a far too dense, huge, and abstract official spec doesn’t help matters.

In any case, what good library writers and third-party documenters of core functionality do is list and describe objects, functions, and other random bits, maybe with a tutorial or two sprinkled in. The most crucial piece of this is describing inputs and outputs for functions.

One could argue that this documentation should be done anyway, and therefore, having types of inputs and outputs enforced by the language itself would be a good thing. Since someone has to write it, it might as well be written in the code itself, right?

In Haskell, and more and more frequently in documentation by JavaScript library writers who might wish JavaScript were a little more like Haskell, types are described by the Hindley–Milner type system. Most JavaScript documentation doesn’t use this system, but it does show up in the docs for Ramda and Sanctuary (we’ll cover this library later).

It looks something like this:

add :: Number -> Number -> Number

There is much more to it, but these are the most popular parts. add is the function name, followed by two inputs of type Number , and one output Number . But wouldn’t it be clearer like this?

add :: (Number, Number) -> Number

In a way it would, but assuming add is curried (which is a good assumption for Haskell and aspirational JavaScript as used in Ramda), we should think of applying (calling the function with) the first Number as producing a new function that waits for the second number. For example, if we applied a 1 , we could have a new function with the type:

addOne :: Number -> Number

We covered this earlier when our addition function turned into an addOne function after we gave it only one parameter (a 1 ) instead of two parameters right away. If we give addOne another number, it will output a number.

So there are two points here. The first is that in some programming, the assumed arity (how many parameters are passed in) is 1 , because things are understood to be curried by default.

The second point is that type declarations don’t just document what functions do, they also indicate how functions can collaborate with functions. So if you know that a function produces a number, and you use its output as input to a function that takes a string, then you shouldn’t be surprised if something goes wrong (a compilation or runtime error in some languages and libraries, or maybe just a confused result in JavaScript).

Less intuitive aspects of types

On the seemingly less awesome side of type documentation (and code itself), the functional style prefers short variable names, which can be a bit of a shock. Take a look at the type signature for Haskell’s map function (specifically for lists):

map :: (a -> b) -> [a] -> [b]

The grouping of the parentheses  (a -> b) indicates that map takes a function as its first argument, which itself takes one input ( a ) and has one output ( b ). map also takes an array of [a] . Then it outputs an array of [b] . The a and b seem like excellent candidates for very bad names (short and nondescriptive), but there is a logic behind them.

map ’s first parameter is a function that transforms an a into a b . It applies that function to a list full of a s, and transforms it into a list of b s, which it returns. All it’s describing is what needs to remain the same, and what may be different. A function that transforms a number into a boolean must be used to transform a list of numbers into a list of booleans. But map doesn’t care what type a and b are specifically.

When you declare a variable or constant, that is different because you’re labeling a concept of an actual specific value. Here, the type variables are just indicating what is the same and what is different. This is common with higher-order functions like map , where the types a and b actually apply to many types. By contrast, note that in the previous add function, the inputs and outputs were specific to a Number type.

It can get a little complicated. This is the type description from the concat function of Maybe in Sanctuary:

Maybe#concat :: Semigroup a => Maybe a ~> Maybe a -> Maybe a

The Maybe# indicates the this object (an object of type Maybe ) that has the concat function available. The Maybe a parts describe normal inputs and outputs, and a type variables could be anything, but they’re all the same and wrapped up in Maybe s. This is kind of like what we saw before when list items were wrapped up in arrays with [a] and [b] .

We have two types of arrows in Maybe a ~> Maybe a -> Maybe a , though. Working from the right, the last arrow is -> , which isn’t new. It’s just indicating input headed for output. The first one is ~> (squiggly arrow), indicating that an implicit parameter (the this ) is also in the mix.

But isn’t this bad?

Unlike in OOP, in functional programming, it’s much more common to avoid this in favor of passing explicit parameters. Where we use this in this chapter, it is done mostly as a way to namespace functions. That goes for R (for Ramda functions) and S (for Sanctuary functions and objects).

One key thing to note is that these variables provide a namespace and utility functions, but they aren’t intended to hold state “variables” that are changed.

In OOP, stateful objects (with mutable values) are arguably better than scattered nonlocal variables, but in FP, we should consider R and S to provide the same utility as modules , rather than classes or objects .

The Semigroup a => bit is new too. That just means that this function ( concat of Maybe ) is implementing a function from the Semigroup typeclass. We’re not going to get into typeclasses. There is no decent analogous structure for a typeclass in JavaScript. It could be thought of as an interface in some OOP languages, or as a contract that must be fulfilled. In Chapter 9 , we discussed empty parent classes as a faulty but possible demonstration of this idea.

Anyway, if you spend some time in functional corners of JavaScript, you’ll hear types discussed and see functions notated with their type signatures from time to time.

Burritos

This section might be about burritos. It might be about something else. I can’t explain everything about burritos in a few pages. They’re too complex and eating too many at once is a mistake. Indigestion and regurgitation full of new metaphors are both common results.

For the sake of your future investigations, burritos might involve any of the following:

  • Monoids
  • Functors
  • Applicatives
  • Monads
  • Maybe more?!

Wow. I get a red underline marking all of those as misspellings. We’re in serious jargon territory, apparently. They’re complicated, and if this is your first time with them, no explanation is going to work better than some actual code. And this is why people are so quick to explain these things by analogy, and often call anything related to them “burritos.” Sometimes this approach comes from someone who doesn’t want to explain everything that leads to the practical stuff they want to cover (like me), or as an out for people who feel they don’t know enough about functional programming or deep mathematical category theory to really do the topic justice (like me).

The real problem is, people can “get” the concept of a “queue” (for instance) without much difficulty. It’s just one thing that’s conceptually easy, and the real-life analogs (e.g., lines of people waiting for something) are both clear and indicated by the name of the thing. The same goes for “stack.” This is, however, less the case for “linked lists” and “Bloom filters.”

If you try to understand every burrito-like thing (functional abstract data types , or ADTs) at once, you’re up against something like Figure 11-1 .

Figure 11-1. Haskell burritos

Monads are usually the burrito in question. And yes, you could try to start there, but all those arrows in the diagram point from “simple thing” to “more complex thing,” which indicates that monads are pretty complex. So if you want a deep dive into this stuff, try starting at the functor ( Figure 11-2 ). You can definitely understand that one as easily as a queue or a stack. Basically, a functor has a map function and some rules. In fact, since you’re certainly already using map with arrays, you’re not starting from scratch here.

Figure 11-2. The Fantasy Land specification for burritos in JS

An actual explanation

So there are these words that fly around, like functors and monads . They’re intimidating at first because they’re abstract, and it’s common to see them explained in terms of other things you might not understand. They are abstract data types (ADTs), just like linked lists and stacks. They are defined by the operations you can perform on them and rules for how they can be used.

A stack isn’t a thing you use directly, but you can build something that implements a stack interface (i.e., it has push and pop functions), according to the rules of how a stack should behave (i.e., it stores things in a “last in, first out” kind of way).

Similarly, you can create all the scary-seeming functional ADTs (probably using objects in JavaScript’s case, but maybe just collections of functions) that implement the interface of “abstract data types” according to their rules.

My apologies if this is a letdown, but the goal of this section of this chapter is to give you some concrete experience with useful functional APIs. If you want some further reading on functional programming and functional ADTs, I’ll keep a list updated with some videos, tutorials, and books about burritos as I find them.

Introducing Sanctuary

Speaking of a useful API, install Sanctuary on the command line:

npm install sanctuary

Then in your program, do this:

const {create, env} = require('sanctuary');
const S = create({checkTypes: true, env: env});

You’re left with an S object. Like other functional libraries, Sanctuary has a massive interface that might be intimidating. As of this writing, there are over a hundred properties defined on S . A lot of them ( compose , inc , pluck , etc.) should look familiar after our time with Ramda. There is a bit of a difference, however. With Ramda, adding "hello" and 3 just returns NaN :

R = require('ramda');
R.add("hello", 3);
// NaN

With Sanctuary:

const {create, env} = require('sanctuary');
const S = create({checkTypes: true, env: env});
S.add("hello", 3);

you get this:

TypeError: Invalid value
add :: FiniteNumber -> FiniteNumber -> FiniteNumber
       ^^^^^^^^^^^^
            1
1)  "hello" :: String
The value at position 1 is not a member of 'FiniteNumber'.

And with a stack trace. Sanctuary has runtime type-checking errors (for the functions it has defined). That’s pretty awesome, but possibly not what you’d want in production. If that’s the case, you can initialize it without type checking like this:

const {create, env} = require('sanctuary');
const S = create({checkTypes: false, env: env});

Now Sanctuary won’t type-check its functions, but be careful:

S.add('hello', 3)
// 'hello3'

That’s default JS behavior, but Ramda and Sanctuary not being in agreement on nonstandard behavior could cause some confusion if you’re using both. Also, just like lodash and Ramda have different interfaces (Ramda sensibly puts the function first), Ramda and Sanctuary also don’t always have the same functions or the same interfaces for those functions that they share.

Regardless, Sanctuary has a lot of functions that are good for functional programming (like Ramda), and it even has a type checker if we want one. Awesome. Also like Ramda, the parameters for its higher-order functions (like find and reduce ) follow the “function-first” idea, so it’s easy to compose functions like this:

const getAThree = S.find(x => x === 3);

Or point-free:

const getAThree = S.find(R.equals(3));

Either way, we can apply the array to getAThree :

getAThree([3, 4]);

And then something weird happens. We don’t just “get a three,” we get:

Just(3)

And for an array without a 3 in it:

getAThree([8, 4]);

we get:

Nothing()

Sanctuary’s motto

Sanctuary’s motto is “Refuge from unsafe JavaScript.” It prefers giving Nothing and Just rather than null . This might seem awkward to handle, but it’s much better than being surprised by “undefined method” errors.

The null Object Pattern, Revisited!

These Nothing and Just values from Sanctuary should remind us of something. We’re actually working with a similar concept to null objects (covered in Chapter 9 ). Just and Nothing will remain a mystery for just a bit longer, but let’s see how they might apply to our Person / AnonymousPerson code.

Let’s see what we had when we used a decorator to wrap our null objects:

class Person {
  constructor(name){
    this.name = new NameString(name);
  }
};
class AnonymousPerson extends Person {
  constructor(){
    super();
    this.name = null;
  }
};
class NameString extends String{
  capitalize() {
    return new NameString(this[0].toUpperCase() 
               + this.substring(1));
  };
  tigerify() {
    return new NameString(`${this}, the tiger`);
  };
  display(){
    return this.toString();
  };
};
class NullString{
  capitalize(){
    return this;
  };
  tigerify() {
    return this;
  };
  display() {
    return '';
  };
};
function WithoutNull(person){
  personWithoutNull = Object.create(person);
  if(personWithoutNull.name === null){
    personWithoutNull.name = new NullString;
  };
  return personWithoutNull;
};

Not bad. It cost us quite a few lines, but we kept the billion-dollar mistake ( null ) at bay.

But using Just and Nothing provide a really easy way to do this. Here’s what our new implementation looks like:

const {create, env} = require('sanctuary');
const S = create({checkTypes: false, env: env});

class Person {
  constructor(name){
    this.name = S.Just(name);
  }
};
class AnonymousPerson extends Person {
  constructor(){
    super();
    this.name = S.Nothing();
  }
};
const capitalize = (string) => string[0].toUpperCase()
                               + string.substring(1);
const tigerify = (string) => `${string}, the tiger`;
const display = (string) => string.toString();

Starting from the bottom three functions, instead of messing around with specialty forms of string objects with functions implemented on them, we opt for functions that don’t rely on an implicit this , and we’ll pass our strings as explicit inputs.

We completely got rid of our String extended classes. Instead of setting the names of our Person and AnonymousPerson to new instances of those extended classes, our constructors assign name to what we can think of as a wrapped name (for Person ) or a wrapped null (for AnonymousPerson ).

Unsurprisingly, our original tests will fail:

test("Displaying a person", (assert) => {
  const personOne = new Person("tony");
  assert.equal(personOne.name.capitalize().tigerify().display(),
               'Tony, the tiger');
  assert.end();
});
test("Displaying an anonymous person", (assert) => {
  const personTwo = new AnonymousPerson(null);
  assert.equal(WithoutNull(personTwo).name.capitalize().tigerify()
    .display(), '');
  assert.end();
});

The first failure we get is:

assert.equal(personOne.name.capitalize().tigerify().display(),
                              ^

TypeError: personOne.name.capitalize is not a function

This is because we no longer have a “fluent interface” of string functions returning strings to chain with another function. We need a way to apply a function to a Just or Nothing , then rewrap the value and pass it along. To do this, we use map :

test("Displaying a person", (assert) => {
  const personOne = new Person("tony");
  assert.equal(personOne.name.map(capitalize).map(tigerify)
    .map(display), 'Tony, the tiger');
  assert.end();
});
test("Displaying an anonymous person", (assert) => {
  const personTwo = new AnonymousPerson(null);
  assert.equal(personTwo.name.map(capitalize).map(tigerify)
    .map(display), '');
  assert.end();
});

This is the hard part. When you call map on a Just or a Nothing , the function will apply to the values inside of Just , but Nothing will pay no attention to the function applied through map . Nothing will just pass along another Nothing .

What? I thought map was for Array!

That is definitely the case in most programming you’ll likely do in JavaScript. However, in the functional world, map has another role of applying a function to objects of various kinds. It might be hard to unify the ideas of “mapping over an iterable” and “mapping over Just or Nothing ,” but after working with it a bit, you should find it clearer.

If that doesn’t make sense, don’t worry. For now, it’s okay if you think of it as a completely new type of map that has nothing to do with the map that works on iterables. This new kind “unwraps, applies a function, and rewraps” Just and Nothing .

There’s another explanation here, and if it doesn’t sink in yet, that’s okay. One list-based type signature for map is this:

map :: (a -> b) -> [a] -> [b]

And the signature for map as related to Just and Nothing could be the following:

map :: (a -> b) -> Maybe a -> Maybe b

We’ll discuss this in a bit, but Just and Nothing are both types of Maybe .

We’re getting closer, but our tests now fail like this:

// for personOne
expected: 'Tony, the tiger'
actual:   Just("Tony, the tiger")

// for personTwo
expected: ''
actual:   Nothing()

Interestingly enough, our display function no longer actually does anything. Mapping over a Just('String') with toString still gives us Just('String') , and Nothing() stays as Nothing() as well. The tests are still failing, but we have a bit less code to deal with:

...
assert.equal(personOne.name.map(capitalize).map(tigerify), 
             'Tony, the tiger');
...
assert.equal(personTwo.name.map(capitalize).map(tigerify), '');
...

So how do we unwrap our Just and Nothing ? We can use the S.maybeToNullable function from Sanctuary:

test("Displaying a person", (assert) => {
  const personOne = new Person("tony");
  assert.equal(S.maybeToNullable(
                 personOne.name.map(capitalize).map(tigerify)),
               'Tony, the tiger');
  assert.end();
});
test("Displaying an anonymous person", (assert) => {
  const personTwo = new AnonymousPerson(null);
  assert.equal(S.maybeToNullable(
                 personTwo.name.map(capitalize).map(tigerify)),
               '');
  assert.end();
});

This gets us closer. Our first test passes, but our personTwo test fails like this:

expected: ''
actual:   null

While S.maybeToNullable unwraps the Just without a problem, it gives us the billion-dollar mistake for our Nothing . If you look at what’s actually happening, it’s not too surprising:

S.maybeToNullable(S.Nothing());

We should expect that to return null . We will take care of the failing test in a minute, but first, “ maybeToNullable ”? What’s a Maybe anyway? Try these:

Object.getPrototypeOf(S.Just());
Object.getPrototypeOf(S.Nothing());

They both return this for their prototype:

Maybe {
  '@@type': 'sanctuary/Maybe',
  ap: [Function],
  chain: [Function],
  concat: [Function],
  empty: [Function],
  equals: [Function],
  extend: [Function],
  filter: [Function],
  map: [Function],
  of: [Function],
  reduce: [Function],
  sequence: [Function],
  toBoolean: [Function],
  toString: [Function],
  inspect: [Function: inspect] }

So Just and Nothing are both some kind of Maybe ? Is that a perfect academic description? No, but it’s a workable one. Now let’s fix the tests:

test("Displaying a person", (assert) => {
  const personOne = new Person("tony");
  assert.equal(S.fromMaybe('',
                 personOne.name.map(capitalize).map(tigerify)),
               'Tony, the tiger');
  assert.end();
});
test("Displaying an anonymous person", (assert) => {
  const personTwo = new AnonymousPerson("tony");
  assert.equal(S.fromMaybe('',
                 personTwo.name.map(capitalize).map(tigerify)),
               '');
  assert.end();
});

Now our tests should be passing again!

Functional Refactoring with Maybe

Instead of S.maybeToNullable , we used S.fromMaybe to return a blank string ( '' ) if the Maybe ( Nothing or Just ) is a Nothing . If it is a Just , it unwraps the value.

So if both names are actually Maybe all along, can we create the wrapper based on the input? Yes. And if the only difference between a Person and an AnonymousPerson is that they have different name values, we don’t actually need the subclass anymore:

class Person {
  constructor(name){
    this.name = S.toMaybe(name);
  };
};

And in our tests, we can declare both objects as a new Person :

...
  const personOne = new Person("tony");
...
  const personTwo = new Person(null);
...

So what does our code look like now?

const {create, env} = require('sanctuary');
const S = create({checkTypes: false, env: env});

class Person {
  constructor(name){
    this.name = S.toMaybe(name);
  };
};
const capitalize = (string) => string[0].toUpperCase()
                               + string.substring(1);
const tigerify = (string) => `${string}, the tiger`;
const display = (string) => string.toString();

const test = require('tape');
test("Displaying a person", (assert) => {
  const personOne = new Person("tony");
  assert.equal(S.fromMaybe('',
                 personOne.name.map(capitalize).map(tigerify)),
               'Tony, the tiger');
  assert.end();
});
test("Displaying an anonymous person", (assert) => {
  const personTwo = new Person(null);
  assert.equal(S.fromMaybe('',
                 personTwo.name.map(capitalize).map(tigerify)),
               '');
  assert.end();
});

As far as refactoring, we can compose the capitalize and tigerify functions, which simplifies our assertions:

...
const capitalTiger = S.compose(capitalize, tigerify);
...  
assert.equal(S.fromMaybe('', personOne.name.map(capitalTiger)),
             'Tony, the tiger');
...
assert.equal(S.fromMaybe('', personTwo.name.map(capitalTiger)), '');
...

But we have more possibilities. In order to not break the second test, we apply this only to the first assertion:

assert.equal(personOne.name.map(capitalize).chain(tigerify),
             'Tony, the tiger');

Instead of using two map functions and then wrapping with a fromMaybe , we can use chain to get an unwrapped value back from tigerify . Note that if tigerify itself returned a Maybe , that wouldn’t work.

Better yet, we can use chain in combination with our composed capitalTiger :

assert.equal(personOne.name.chain(capitalTiger), 'Tony, the tiger');

By the way, in case you’re wondering why we can’t just call personOne.name as an argument to the capitalTiger function, here’s the issue:

...
assert.equal(capitalTiger(personOne.name), 'Tony, the tiger');
...

// leads to this error

   expected: 'Tony, the tiger'
   actual:   'Just("tony"), the tiger'

capitalTiger is supposed to take a string, not a Maybe . Also, note that the type checker wouldn’t save you here, because capitalTiger doesn’t have its type declarations registered like the S. functions do.

Anyway, if we want to allow capitalTiger to access the Maybe , we can lift it, instead of mapping with personOne.name.map(capitalTiger) :

...
assert.equal(S.lift(capitalTiger, personOne.name), 'Tony, the tiger');
...

This has the same result as the earlier map , but is conceptually a little different. Instead of mapping over the Maybe with an ordinary function, you’re promoting your function to work with the Maybe . You can think of it as making your function special (“lifted”) rather than passing it as a dumb argument to map (which itself is already special).

In either case, you can also call .value on the Just to unwrap the value:

// take your pick

// map
assert.equal(personOne.name.map(capitalTiger).value,             
             'Tony, the tiger');

// chain (unwraps the value, so no need for .value)
assert.equal(personOne.name.chain(capitalTiger), 'Tony, the tiger');

// lift
assert.equal(S.lift(capitalTiger, personOne.name).value, 
             'Tony, the tiger');

As for the second test, we could create another function (probably composed with capitalTiger ) that would test for Nothing and give us the empty string, but a better option is just using the lowercase S.maybe function.

It takes a value, a function, and a Maybe , and returns the value when the Maybe is not a Just . Otherwise, it returns the result of the function applied to the Maybe ’s value. It’s perfect for what we want:

assert.equal(S.maybe('', capitalTiger, personTwo.name), '');

But reduce would also work:

assert.equal(personTwo.name.reduce(capitalTiger, ''), '');

It ignores the function (because it is a Nothing ) and returns '' .

It’s okay if the interfaces provided by Ramda and Sanctuary don’t make perfect sense or are overwhelming. We covered a lot of ground here. What’s nice is that you can incrementally add this style of programming to your JavaScript. Aside from the type signatures (which are good to know how to read, but you don’t need to write), there’s no new syntax to learn, and no compilation step necessary.

Functional Refactoring with Either

If you’re not too confused by Maybe , you might be interested in Either . This section won’t go into too much depth on it, but as far as motivation, our last test had this line:

assert.equal(S.fromMaybe('', personTwo.name.map(capitalTiger)), '');

The second '' makes sense, as that’s what we’re testing against, but isn’t the test a little bit late to be determining that our value should change from a Nothing into an empty string? What if we wanted to test it again? Would we have to keep specifying that value? Also, if we want to keep our tests symmetrical, should we really have to specify the empty string for our personOne test as well?

Fortunately, there’s a way to specify what we want our Nothing value to unwrap to before we’re unwrapping it. Unfortunately, how to do so is a little complicated. Let’s look at the code we would need:

const {create, env} = require('sanctuary');
const S = create({checkTypes: false, env: env});
const R = require('ramda');

class Person {
  constructor(name){
    this.name = S.maybeToEither('', S.toMaybe(name));
  }
};

const capitalize = (string) => string[0].toUpperCase()
                               + string.substring(1);
const tigerify = (string) => `${string}, the tiger`;

const capitalTiger = S.compose(capitalize, tigerify);

const test = require('tape');
test("Displaying a person", (assert) => {
  const personOne = new Person("tony");
  assert.equal(S.either(R.identity, capitalTiger, personOne.name),
               'Tony, the tiger');
  assert.end();
});
test("Displaying an anonymous person", (assert) => {
  const personTwo = new Person(null);
  assert.equal(S.either(R.identity, capitalTiger, personTwo.name),
               '');
  assert.end();
});

The new pieces here are:

  • We’re requiring Ramda.
  • We assign our name property by converting the value to a Maybe and then an Either .
  • Our tests are symmetrical and use S.either .

Let’s talk about those last two bullet points. First, this line:

this.name = S.maybeToEither('', S.toMaybe(name));

As before, in the non- null case, S.toMaybe makes a Just that holds the name value that we pass in. Then, that Just is converted (through S.maybeToEither ) into a Right that also holds the name .

In the null case for name , S.toMaybe creates a Nothing , which is the same as before. Then, S.maybeToEither turns that Nothing into a Left , and unlike Nothing , Left can hold a value. The value that it is set to hold is a blank string, '' .

Because the Left is holding that value from the beginning, we can pull it out at the end in the same way we can pull out the value from the Right —namely, with these in the tests:

assert.equal(S.either(R.identity, capitalTiger, personOne.name), '');
assert.equal(S.either(R.identity, capitalTiger, personTwo.name), '');

The S.either function says: if it’s a Left , apply the first parameter function to it ( R.identity ), and if it’s a Right , apply the second parameter function to it ( capitalTiger ). That’s okay , but it’s also a bit prescriptive.

With a bit better of an understanding, we can use map instead. Left and Right are both Either subtypes. Left acts a little like Nothing , in that unlike Right (or Just ), it will ignore when you try to map functions to it. That means our tests could also be the following:

assert.equal(personOne.name.map(capitalTiger).value, 'Tony, the tiger');
assert.equal(personTwo.name.map(capitalTiger).value, '');

This is more in line with how we expect Left and Right to behave. The Right (our personOne.name ) goes along with the map ’s function ( capitalTiger ) in the same way a Just would. The Left (our personTwo.name ) disregards the map ’s wishes, just like a Nothing would do with map . Unlike Nothing , however, the Left is holding onto a value (just like a Just or a Right ). That means we can pull that attribute out with .value for both our Left and our Right .

Note that we couldn’t use map followed by .value when personTwo.name was a Nothing because a Nothing ’s value is actually undefined in Sanctuary.

As a final curiosity, you might think that this is a fairly complicated way to get our Left value:

this.name = S.maybeToEither('', S.toMaybe(name));

First we convert to a Maybe , and then to an Either . The reason is that a Left can hold a value, including null . To illustrate:

S.Either.of(null)
// returns Right(null) not Left(null)!

// vs. 

S.toMaybe(null)
// returns Nothing()

As of this writing, you’ll need to first get a Nothing , and then convert it to a blank string containing Left via:

S.maybeToEither('', S.toMaybe(name));

Based on what’s in the main branch of Sanctuary, we should be seeing a more direct option that would let us do: S.toEither('', name) , but for now (Sanctuary version 0.11.1), we’re stuck with the workaround. That said, if you’re interested in checking out other functional libraries, Folktale has an Either.fromNullable function that would be perfect for this.

Before we leave this example completely, notice how short our Maybe and Either versions are in comparison to the null object wrapping code we made in Chapter 9 . Admittedly, it’s not quite a fair fight, because in the null object wrapper we had the artificial restriction of not touching certain parts of the code.

Learning and Using Burritos

You might be thinking that there are an enormous number of ways to use Maybe and Either . And that is true. APIs as big as Maybe ’s can be intimidating. If you look at the Sanctuary documentation , you’ll see that Maybe implements the following ADTs from the “Fantasy Land” functional JS specification: monoid, monad, traversable, extend, setoid, and alternative. Implementing these also means that functor, apply, applicative, chain, foldable, and semigroup are implemented according to the dependency rules of the Fantasy Land spec.

The good news is, if you like that sort of thing, Maybe and Either have friends. A promise is similar to what is typically called a future or task . List is not unlike how you might use an array. There are a ton of other structures that implement these ADTs.

A public service announcement: monads (and their friends from Figures 11-1 and 11-2 and the previous paragraph) are at risk of being fetishized in a way that has been the case for design patterns, data structures, algorithms, and even math itself. Not knowing all of the trivia (let alone the deep mathematical basis) of monadic laws should not stop you from using useful objects and functions when you find them. “I’m not a math person” and a terribly architected website-producing company interviewing with “How do you reverse a linked list?” are evil twins.

Just because in some contexts, blocks of knowledge are unfairly treated as a binary of known or unknown does not mean we should perpetuate that. If you worked through the last section and used the Maybe and Either interfaces, you’ve used a monad, as well as some other good abstractions. You will never have to make your own (when is the last time you implemented a linked list in JavaScript because arrays weren’t good enough?), but you could. And if you did make your own, you could make them correct by someone’s definition. You could add a few functions that you like even if they don’t fit in with other people’s ideas. You could leave stuff out. And you could call them burritos if you wanted.

The thing is, you can have objects and functions that don’t conform to precise definitions but are still useful. If you’re creating them, then the interfaces and laws of what makes a functor versus an applicative versus a monad should be important to you. If you’re just using them, try things out, but focus on the interfaces and don’t get hung up on every definition and law. If you’re interested in writing or using something that conforms to the interfaces and rules of high-level functional programming abstractions, however, you should look into the aforementioned Fantasy Land spec , which breaks things down into digestible pieces and provides links to implementations of the spec (that means code you can use).

What’s awesome about Haskell (and Lisp, and Prolog, and other opinionated languages) is that they force you into a certain frame of mind. The same goes for spreadsheets, calculators, calendars, and so on. What’s awesome about JavaScript is that we have a massive platform and can write in so many different ways. We used a couple of really great high-level abstractions, and cut down on earlier code significantly.

Deeper into Functional Programming

If you’re looking to get deeper into FP, you might find yourself hitting a wall by only using JS directly or with libraries that don’t require a compilation step. For compiles-to-JS languages, you have some interesting options:

  • TypeScript
  • PureScript
  • ClojureScript
  • Elm

If you want to explore FP on its own, without worrying about compiling to JavaScript, then you could look into these:

  • Haskell
  • Scheme/Clojure (Lisp variants)
  • Erlang
  • Scala

As of this writing, there are many other choices out there in both categories, and many more are bound to be developed. The point is that you shouldn’t feel restricted by only working in JavaScript. Good ideas come from everywhere. It’s not uncommon to see a standard way of working in one language appear as an innovation in another.

Moving from OOP to FP

As mentioned before, if you’re jumping paradigms like OOP to FP, it’s probably much too large of a change to be called refactoring anymore. Despite that, it’s likely that you will find working through a similar process helpful: make small steps, keep code changes under version control, keep a passing test suite.

Return of the Naive Bayes Classifier

Let’s briefly return to our NBC example from Chapters 6 and 7 . It would be great to show the full process of “restructuring” (or perhaps “refactoring,” if you’re taking a broad view of the term), but there are so many changes that, instead, after the code sample I’ll offer some general advice if you ever decide to change the code this radically. Here’s the functional version of our NBC:

// naive_bayes_functional.js
R = require('ramda');

const smoothing = 1.01;

function wordCountForLabel(testWord, relevantTexts){
  const equalsTestword = R.equals(testWord);
  return R.filter(equalsTestword, _allWords(relevantTexts)).length;
};

function likelihoodOfWord(word, relevantTexts, numberOfTexts){
  return wordCountForLabel(word, 
                           relevantTexts) / numberOfTexts + smoothing;
};

function likelihoodByLabel(label, newWords, trainedSet){
  const relevantTexts = textsForLabel(trainedSet.texts, label)
  const initialValue = trainedSet.probabilities[label] + smoothing;
  const likelihood = R.product(
    newWords.map(newWord => 
      likelihoodOfWord(newWord, 
                       relevantTexts,
                       trainedSet.texts.length))) * initialValue;
  return {[label]: likelihood}
}

function textsForLabel(texts, label){
  return R.filter(text => text.label === label)(texts);
}

function _allWords(theTexts){
  return R.flatten(R.pluck('words', theTexts));
};

function addText(words, label, existingText = []){
  return R.concat(existingText, [{words: words, label: label}]);
};

function train(allTexts) {
  const overTextLength = R.divide(R.__, allTexts.length);
  return {texts: allTexts,
          probabilities: R.map(overTextLength, 
                               R.countBy(R.identity,
                                         R.pluck('label', allTexts)))};
};

function classify(newWords, trainedSet){
  const labelNames = R.keys(trainedSet.probabilities);
  return R.reduce((acc, label) => 
    R.merge(acc, likelihoodByLabel(label, newWords, trainedSet))
            , {}, labelNames);
};

module.exports = {_allWords: _allWords,
                  addText: addText,
                  train: train,
                  classify: classify}

And then the tests:

// naive_bayes_functional_test.js
const NB = require('./naive_bayes_functional.js');

const wish = require('wish');
describe('the file', () => {
  const english = NB.addText(['a', 'b', 'c', 'd', 'e', 'f', 'g',
                      'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q'],
                      'yes')
  const moreEnglish = NB.addText(['a', 'e', 'i', 'o', 'u'],
                      'yes', english)
  const allTexts = NB.addText(['あ',     'い',    'う',     'え',     'お',
                       'か',     'き',    'く',    'け',    'こ'],
                       'no', moreEnglish)

  var trainedSet = NB.train(allTexts);

  it('works', () => {
    wish(true);
  })
  it('classifies', () =>{
    const classified = NB.classify(['お', 'は', 'よ', 'う', 'ご', 'ざ', 'い',
                                    'ま', 'す'], trainedSet);
    wish(classified['yes'] === 1.833745640534112);
    wish(classified['no'] === 3.456713680099012);
  });
  it('number of words', ()=>{
    wish(NB._allWords(trainedSet.texts).length === 32);
  });

  it('label probabilities', ()=>{
    wish(trainedSet.probabilities['yes'] === 0.6666666666666666);
    wish(trainedSet.probabilities['no'] === 0.3333333333333333);
  });
});

There are major differences from what we had before. Here are some of them:

  • The algorithm has been slightly altered, leading to different values for “likelihoods,” but that should not affect the majority of classification outcomes.
  • Rather than exporting a class, we export individual functions.
  • There is no this anywhere in the code.
  • Because there is no this or other state variables, we have to “carry around” all of the state that we need as return values.
  • As a consequence of this, our train and classify functions are now idempotent and pure: same input, same output. No side effects.
  • Every function returns something useful.
  • The addText function is also idempotent, but we’re passing the return value of the early calls to the later ones. That is how we build the set of data.
  • It is shorter, but the Ramda functions make the code fairly dense in places.
  • We also dropped the sets and maps. It’s worth exploring them, but they’re not as flexible as objects and arrays.
  • The module becomes just a namespace. Nothing in it is meant to be mutable, so it doesn’t hold any state or data—just functions producing output that is used as input to other functions.
  • The FP code is shorter.
  • In the end, you’ll have code that is focused on explicitly transforming your data, “pipelining” it through different operations rather than having multiple states on objects.

As far as getting to this point, the first thing to know is restructuring from OOP to FP is not easy. Some steps may seem counterintuitive if most of your experience is in moving from procedural to OOP.

In no particular order, here are some of the steps you may find yourself taking:

  • Have good high-level tests in place. If something stops working, undo your changes.
  • Make every function that isn’t returning anything useful return the main object, probably with return this at first.
  • Change all of the this references to explicitly refer to the object, like Classifier (in this case).
  • Flatten out any objects and subobjects that you can.
  • Move properties out of the objects.
  • Replace state variables with queries.
  • If you have trouble doing this, consider passing in the old state as part of queries until the state eventually just turns into inputs to functions.
  • You’ll probably make the code look worse before it looks better, as you will want to bring things out of structure before creating new structure. You might add duplication, pass around more parameters, and/or introduce unnecessary functions and poorly named variables as you go.
Why Didn’t We Compose More Functions?

There are plenty of ways to combine functions (e.g., R.compose , inlining, creating an outer function that takes in all parameters), and it might seem obvious that we could have combined the train function with either the addText function or the classify function. 

The first question is why do we need the individual functions as opposed to high-level combined ones? The reason for not combining train and addText is that the interface provided by addText is most useful if it’s used a few times to build a bigger set of data. Training it at the same time would mean repetitious or more complicated calculation. The reason for not combining train and classify is that if the training data set were large enough, it could take a very long time to train. We want to keep that separate, as it will be easier to do things like pass it off to a separate process. Also, we were interested in just testing with one classified set. It’s useful to not repeat the training step for every test.

But why we didn’t make those functions available anyway? To keep the API smaller and simpler, and provide only one reasonable way to use the library.

All in all, it’s hard to move from structure to structure—possibly harder than moving from unstructured to structured code (either OOP or FP). You can strike a balance between the two approaches, but mutating high-level state (the properties of instances of any objects, sets, maps, etc.) that you introduce is very different than simply relying on input and output.

Rewrites

Keep in mind that moving from OOP to FP is just one type of restructuring. If you’re intending to move from one framework to another, a “rewrite” is probably what you’ll end up doing. Although it’s possible to do this slowly and carefully through a strangler app that slowly takes more and more responsibilities from the legacy app , it’s hard to not allow that to lead to a fractured user experience for quite a while.

A full rewrite, where the old app is supported until the new one is “good enough” (unfortunately, this is usually pretty ambiguous), is an especially difficult problem, for a few reasons:

  • Feature parity for two apps in different frameworks is hard to define.
  • It’s easy for design changes and new features to become “essential” to the new app, increasing the scope from feature parity to something else.
  • A solid (possibly “phased”) cutover plan/upgrade path for all customers should be defined.
  • If the new version demands new skills to build, your current team, though experts on the old app, might not have great experience with the technologies required for the rewrite.
  • “Business rules” that may be faithfully executed in the old app can be lost in translation, mistaken for bugs or details that don’t matter.
  • Progress can be very difficult to demonstrate.
  • It’s very difficult to estimate how long a rewrite will take.

Overall, restructuring between paradigms and rewriting between frameworks are both very hard. They’re not simple, mechanical processes like refactoring can be. On a multidisciplinary team with various working styles and priorities, rewrites will mean very different things to different people.

The principles of moving in small, confident steps, backed up by tests and version control, are helpful. Aside from that, the best thing to do is communicate clearly how long things will take, including admitting when your estimates carry assumptions that may prove to be incorrect. When in doubt, double your estimate, and then triple it.

A Rewrite of Your Own

If you’re interested in a mini-rewrite project, try moving the NBC code from OOP to FP style. Or try moving it to FP from the procedural version of the code (before the classifier object sucked in all of the functions). See if your version is similar to that of the previous section. Is it easier to start from scratch or move incrementally? Take a guess at how long it will take, and see how accurate your guess was.

Wrapping Up

In this chapter, we discussed some of the benefits of functional programming, and how a good portion of them are realized through practices we’ve been discussing all along: not reusing variables, avoiding shared state, extracting functions, and preferring Array ’s higher-order functions to for loops.

We also explored some interfaces and libraries (Ramda and Sanctuary) for functional programming along with good old arrays, as well as Maybe , which might be new to you but will hopefully find a place in your toolkit to help squash null , the billion-dollar mistake.

Maybe functional programming will be your new favorite paradigm. If so, I’d encourage you to try something stricter like Haskell, but if that gets intimidating or you miss working in the browser, remember that you can explore the concepts and exploit the interfaces of FP in JavaScript with just a few require statements. FP doesn’t have to be all or nothing.

It’s a huge topic, and in this chapter, we just skimmed the surface. As to what a path toward learning FP could look like, I recommend the following sequence:

  1. Get familiar with the native JS Array ’s higher-order functions (they take a function as input), such as forEach , map , filter , and reduce .
  2. Try out a library like underscore or lodash, which have many more manipulations than what is provided for in native JavaScript.
  3. Get used to composing functions and manipulating arguments with Ramda and/or Sanctuary.
  4. Use Sanctuary, ramda-fantasy, Folktale, or any of a number of other implementations of the Fantasy Land spec that describe burrito-like things from the earlier diagrams.

Along the way, try these out as well:

  • Use Immutable.js or mori to enforce immutability beyond what const and .freeze can easily offer.
  • Try out functional languages that compile to JS.
  • Try out functional languages that don’t compile to JS.   

1 Just kidding—websites are mostly prioritized to serve ads, load a large “hero” graphic (or video! how neat!) after a few seconds, and break your ability to fluidly scroll through the content of a page.