Function boobs or how people love to call them: Higher Order Functions

- Branko are you crazy?
No I’m certainly not!

I just love crazy stuff in JavaScript. One of those things are definitely function boobs. I’m sorry, but I couldn’t find more describable and funnier name for this phenomenon so I’m gonna call it like that.

Foo()(), am I right? Hihi.

Let's dive in!

In your, so far, developer life, you must have seen something like this:

connect(mapStateToProps, mapDispatchToProps)(App);

Did you try to understand what this is and how the hell is it working?

This connect function is called Higher Order Function (HOF).

By definition HOF is a function that accepts and / or returns a function as parameter.

How it works you might ask?

First boob in connect accepts several things. Couple of functions for redux state and actions and some other options which are not the topic here so I’m not gonna cover it.

Second boob is basically return function from connect that accepts react component.

So, main purpose of the connect function is to prepare testament for its child (child that comes from the second boob).

All the information from testament (redux state and actions) is bound to the child’s props when connect is about to die. That’s why we access redux state via props.

Keep in mind that this is not the definition of connect function. This is just an brief explanation how things are working by my understanding.

function connect(state, actions) {
    /* testament preparation */
    const preparedTestament = {...};
    return (component) => {
        return <component props={props, …preparedTestament}
    }
};

So, at the end, connect returns anonymous function that returns react component but with appended props as I described earlier, hence we call it with 2 pars of brackets like this: connect()().

Why it is useful?

While this technique is used widely with connect, withRouter, etc. HOF can be used for custom stuff as well. For e.g. When you want to attach some component (notification sidebar or something like that) to 3 pages in your react app but omit on 4th and 5th.

Yes! Of course that you can use HOF outside of the react! And that’s the point where the real fun begins!

Or, or, you have already used it and you don't know it! Does map, filter, sort, reduce sounds familiar? :)

Conclusion

HOF as concept is definitely something worth exploring on the deeper level so don’t be afraid to use it, don’t be afraid to understand it. It will be easier with time passed by, and with that, a new horizons will open up for you. :)

Thank you for reading good people. 'til next time!

18