Skip to Main Content
Eloquent JavaScript
book

Eloquent JavaScript

by Marijn Haverbeke
January 2011
Intermediate to advanced content levelIntermediate to advanced
224 pages
5h 43m
English
No Starch Press
Content preview from Eloquent JavaScript

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 Application ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Eloquent JavaScript, 3rd Edition

Eloquent JavaScript, 3rd Edition

Marijn Haverbeke
Learn JavaScript

Learn JavaScript

Shaun Wassell

Publisher Resources

ISBN: 9781593272821Errata