A callback function is a function passed as argument to another one, with this technique we can allow our function to call another which will be invoked after the first function finishes running.
Functions are executed respecting the order of their calling from top to bottom, let’s see this example:
And if we call them this way, the output will change:
Got this one, let’s move to the next concept.
Sometimes while coding, it happens that we are in a front of a use case where we will need two functions that work together (or concurrently) to perform a task. Let’s take a simple example of two functions, the first one performs a calculation and the second displays the result.
Another way to do this is to call the output function inside add function:
Let’s bring callbacks now.
With a callback we can let add finish the calculation and after that the output function will be invoked. To do this we should call add function with a callback:
In this example we passed output function as an argument to add function, and when we passed it we didn’t use parentheses! keep this in mind.
These examples are made simple for learning purposes to give you the ability to learn callbacks, in most cases callbacks are used in asynchronous functions where a function has to wait for another function.