Closure and Higher Order Functions in JavaScript

A function can return all kinds of data. However, did you also know that a function can also return another function? 🤯

Watch this tutorial on my YouTube Channel:

Here’s a quick example:

Introducing Higher Order Function

The notion of Higher Order Function is one of the key pillars in functional programming.

In simple terms, a Higher Order Function is a function that either:

  1. Returns another function.
  2. Takes in another function as its argument.

Or do both.

Now you might be wondering, what the heck does this mean? Why is it useful?

In general, it helps us to write cleaner and more maintainable code. Suppose we have an element in the DOM:

We would like to create multiple headings with different colours within the main element. We can achieve this by using Higher Order Function, with the help of 2 other concepts, Factory Function and Closure.

Factory Function

A factory function is a function that manufactures/creates functions, i.e. it returns another function, and that also makes it a Higher Order Function.

But Why Factory Function?

Now, you might be wondering, why do we even bother with Factory Function?

A factory function allows us to store data to its descendants, and it makes our code very declarative and readable.

Consider the following example:

Although this is a trivial example, a key takeaway from here is we can store immutable data within Factory Functions, and have it passed down to its descendants. The descendants no longer need to redeclare or re-compute the data.

Closure

Closure is a fancy word that refers to function defined within another function.

Creating the headings

A heading has 2 components, the heading text and its colour. We will create a Factory Function that takes in a colour argument and return a function that accepts the heading text.

Here’s the result:

Image by Author

Isn’t that neat?

Ok cool, but why can’t we do this?

So why can’t we just create a normal function that takes in a few arguments like the following? It works exactly the same as its Higher Order Function counterpart.

Here are my two cents. Yes, you can, it is a personal preference. Both of them would work just fine. However, it does make a huge difference for a complex function, especially when it takes in several arguments. By using Higher Order Function, we can break down our complex function into smaller declarative functions that respectively take in fewer arguments!

That’s it! That is a quick introduction to Higher Order Functions and Closure.

Web Development. https://acadea.io/learn . Follow me on Youtube: https://www.youtube.com/c/acadeaio