JavaScript Callbacks
- Previous Page JS Static
- Next Page JS Asynchronous
"I will call back later!"
Callback (callback) is a function passed as an argument to another function
This technique allows a function to call another function
Callback functions can run after another function is completed
Function Sequence
JavaScript functions are executed in the order they are called, not in the order they are defined.
This example will finally display "Goodbye":
example
function myFirst() { myDisplayer("Hello"); } function mySecond() { myDisplayer("Goodbye"); } myFirst(); mySecond();
This example will finally display "Hello":
example
function myFirst() { myDisplayer("Hello"); } function mySecond() { myDisplayer("Goodbye"); } mySecond(); myFirst();
Sequence Control
Sometimes you want to have better control over when to execute a function.
Suppose you want to perform a calculation and then display the result.
You can call the calculator function (myCalculator
),save the result, and then call another function (myDisplayer
) to display the result:
example
function myDisplayer(some) { document.getElementById("demo").innerHTML = some; } function myCalculator(num1, num2) { let sum = num1 + num2; return sum; } let result = myCalculator(5, 5); myDisplayer(result);
Or, you can call the calculator function (myCalculator
),and let the calculator function call the display function (myDisplayer
):
example
function myDisplayer(some) { document.getElementById("demo").innerHTML = some; } function myCalculator(num1, num2) { let sum = num1 + num2; myDisplayer(sum); } myCalculator(5, 5);
The problem with the first example is that you must call two functions to display the result.
The problem with the second example is that you cannot prevent the calculator function from displaying the result.
Now is the time to introduce callbacks.
JavaScript Callbacks
A callback is a function that is passed as an argument to another function.
Using callbacks, you can call the calculator function through the callback:myCalculator
),and then let the calculator function run the callback after the calculation is complete:
example
function myDisplayer(some) { document.getElementById("demo").innerHTML = some; } function myCalculator(num1, num2, myCallback) { let sum = num1 + num2; myCallback(sum); } myCalculator(5, 5, myDisplayer);
In the above example, myDisplayer
is the name of the function.
It is passed as a parameter to myCalculator()
.
Remember not to use parentheses when passing a function as a parameter.
Correct: myCalculator(5, 5, myDisplayer);
Error: myCalculator(5, 5, myDisplayer());
When to use callbacks?
The above example is not very exciting.
They are simplified to explain the syntax of callbacks.
The real shine of callbacks is in asynchronous functions, where one function must wait for another function (such as waiting for a file to load).
The next chapter will introduce asynchronous functions.
- Previous Page JS Static
- Next Page JS Asynchronous