Function Composition with Lodash

Justin Fuller Blocked Unblock Follow Following Nov 9, 2017

Have you been reading JavaScript posts lately? Maybe you’ve noticed that functional programming is really popular right now. It’s a really powerful way to program, but can be overwhelming to get started with. Thankfully the most popular NPM package (with 48 million downloads this month) has a very useful functional programming package to help us get started!

In this post we’ll look at how to use Lodash/fp to compose both our own functions, and the Lodash functions that you may already be using today!

Before we start coding — lets be sure that we know what we’re talking about!

Functional Programming:

A method of programming that focuses on using functions as first class variables. It avoids mutating (changing) data, and attempts to treat applications as a linear flow that pieces functions together to create a whole.

Function Composition:

Invoke functions that have been listed, in order, passing the result of each function to the next in the list, and then return the final function result as the result of the whole.

Normally when you compose functions you may do it like this (without knowing you are composing):

const myResult = myFunction(myOtherFunction(myData));

In that example you are giving myFunction the result of myOtherFunction as it’s only argument. Notice the functions would be called from right to left, or inside to outside. We do something similar with function composition.

const getMyResult = compose(

myFunction,

myOtherFunction,

);

const myResult = getMyResult(myData);

To make things clearer I want to define a few goals for our composed functions.