Other Functional Tricks

Before moving on to the next chapter, I would like to show you a few more functional techniques that can, once you’ve gotten used to them, make your programs more succinct.

Operator Functions

When using higher-order functions, it is often annoying that operators are not functions in JavaScript. For example, we had to define the add function earlier in this chapter. Writing these out every time we need them is a pain. One way to get around that is to create an object like this:

var op = {
  "+": function(a, b){return a + b;},
  "==": function(a, b){return a == b;},
  "===": function(a, b){return a === b;},
  "!": function(a){return !a;}
  /* and so on */
};

So, we can write reduce(op["+"], 0, [1, 2, 3, 4, 5]) to sum an array.

Partial ...

Get Eloquent JavaScript now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.