Advertisement
728x90
The callbacks are needed because javascript is an event driven language. That means instead of waiting for a response, javascript will keep executing while listening for other events.
Let's take an example with the first function invoking an API call(simulated by setTimeout) and the next function which logs the message.
javascript
1function firstFunction() {
2 // Simulate a code delay
3
4setTimeout(function () {
5 console.log("First function called");
6}, 1000);
7}
8
9function secondFunction() {
10
11console.log("Second function called");
12}
13
14firstFunction();
15
16secondFunction();
17
18// Output:
19// Second function called
20// First function calledAs observed from the output, javascript didn't wait for the response of the first function and the remaining code block got executed. So callbacks are used in a way to make sure that certain code doesn’t execute until the other code finishes execution.
Advertisement
Responsive Ad
🎯 Practice NowRelated Challenge
JavaScript Coding Exercise 57
Test your knowledge with this interactive coding challenge.
Start CodingAdvertisement
728x90
56of476