JavaScript Callbacks


"I'll return your call later!"

A callback is a type of function that you pass to another function as an argument.

This method enables one function to invoke another function.

A callback function runs once a different function completes its execution.

Function Sequence

JavaScript functions run in the order they are called, not necessarily in the order they are written.

This instance will result in showing the word "Goodbye."

This illustration will result in showing the message "Hello."


Sequence Control

At times, you might want more control over when a function should be executed.

Imagine you need to perform a calculation and show the outcome.

You can employ a calculator function called (myCalculator), save the outcome, and later utilize another function named (myDisplayer) to display the result.

Alternatively, you can invoke a calculator function (myCalculator), and have this function invoke the display function (myDisplayer):

The issue with the initial example is that you need to use two functions to show the outcome.

The issue with the second example is that you can't stop the calculator function from showing the result.

It's time to introduce a callback now.


JavaScript Callbacks

A callback is a function that you give as input to another function.

With a callback, you can invoke the calculator function (myCalculator) using a callback (myCallback). The calculator function will execute the callback once the calculation is complete.

In the given example, the myDisplayer function is referred to as a callback function.

It gets sent to myCalculator() as a parameter.

Note

When you include a function as an argument, avoid using parentheses.

Correct: myCalculator(5, 5, myDisplayer);

Incorrect: myCalculator(5, 5, myDisplayer());

In the given example, the expression (x) => x >= 0 represents a callback function..

It gets sent to removeNeg() as a parameter.


When to Use a Callback?

The provided exanples are not particularly interesting.

They are made simpler to help you learn how callbacks work.

Callbacks excel in asynchronous functions, especially when a function needs to wait for another function, such as waiting for a file to finish loading.

In the upcoming chapter, we will discuss asynchronous functions.