“JavaScript is an event driven language. This means that instead of waiting for a response before moving on, JavaScript will keep executing while listening for other events.”

In JavaScript, functions are objects. Because of this, functions can take other functions as arguments, and can be returned by other functions as well. Functions that do this are called higher-order functions. Any function that is passed as an argument is called a callback function.

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.

When a function simply accepts another function as an argument, this contained function is known as a callback function. Using callback functions is a core functional programming concept, and you can find them in most JavaScript code.

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.

Read also: