Higher Order Functions
Higher-order functions are functions that take other functions as arguments or return functions as their results.
Any function that is passed as an argument is called a callback function.
One of the great advantages of using higher order functions when we can is composition.
We can create smaller functions that only take care of one piece of logic. Then, we compose more complex functions by using different smaller functions.
This technique reduces bugs and makes our code easier to read and understand.
By learning to use higher-order functions, you can start writing better code.
For example, let’s say you want to write a function for multiplication and division. Generally what we will do is write a function for multiplication and another function for division as shown in below example.
Example :
There is nothing wrong with above functions but we are repeating same lines of code except logic which make our code difficult to understand and can cuase bugs. To handle this, we can create smaller functions that only take care of one piece of logic. And pass those smaller functions as callbacks in another function which is higher order function as shown in below example.
Example :
In above example, we have three functions which are common, multi and div. The common function is the higher order function because it is taking other two functions as arguments which are call back functions.