Callback and higher-order functions in JavaScript
Call-back Function
According to Wikipedia,” In computer programming, a callback, also known as a “call-after” function, is any executable code that is passed as an argument to other code; that other code is expected to call back (execute) the argument at a given time”.
We use callback functions to create applications that operate in a synchronous manner. For example, call-back functions are helpful when we need to request data from an external API and we have to wait for the response, but we don’t always want our entire application to stop while our data is being fetched.
There are several advantages of using call-back functions:
- The call-back function makes it easier to split up our code into more reusable and interconnected parts.
- The call-back function allows us to create an abstraction, but what is abstraction? abstraction is hiding details of some code implementation because we do not really care about all that detail. In fact, abstraction helps us to speak about the problems at a higher (or more abstract) level.
higher-order Function
A function that accepts other functions as arguments is called a higher-order function, which contains the logic for when the callback function gets executed. Higher-order functions allow us to deal with actions, not just values.
In order to elaborate on these two concepts let’s take a look at an example:
The ‘ MathOperations ‘ function does not care about how it should do mathematical operations and the level of details. We could use other functions such as factorial or power inside the MathOperations function but instead, we cut them away into other functions, so that we created a new level of abstraction. Thus, the MathOperation function is only concerned with passing and printing input itself but no matter how those operations itself actually work. It is basically delegating the operations to lower-level functions such as power and factorial.