Member-only story
Higher-Order Functions With TypeScript
Explaining HOF in TypeScriped based on examples
In this article, I want to briefly clarify what Higher-Order Functions are and how to use them. If you are not familiar with HOF, then you might be surprised, because you probably work with them on a daily basis if you work with JavaScript or TypeScript.
What are Higher-Order Functions?
A Higher-Order Function is a function that either takes another function as an argument or returns a function. So basically we could say, that a Higher-Order Function is wrapping another function.
So you might ask yourself: Why would a function take another function as an argument?
The easiest way to explain this in the JavaScript ecosystem might be Callbacks. Callbacks are everywhere so Higher-Order Functions are everywhere.
Higher-Order Functions you might know
Let’s look at some popular Higher-Order Functions you definitely have crossed as a JavaScript or TypeScript developer.
setTimeout()
Yes, setTimeout
is a Higher-Order Function. It takes another function as an argument and calls this particular function after a defined amount of time. In this example, after approximately 100 milliseconds.
Array.find()
Array. find()
is also a very popular Higher-Order Function that appears in most projects several times. Actually, it’s even more complex under the hood. Because our function inside find()
just returns a boolean, but Array.find()
itself returns either undefined or the desired element.