Callback Function in Javascript
Authored By: Sanjeet Tripathi
Callback Functions are the functions in Javascript that get executed only after the primary function is done with the execution.
In all the cases, the Callback function is used as the parameter in the primary function.
Join Engineering Communities and Events related to your Career Path.

Why do we need Callback Function?
Callback functions are mostly used because of Asynchronous action in Javascript. Asynchronous Javascript led to the nonstop execution of code, it doesn’t stop the execution of a function until it got completed. Instead, keep executing it in the background and let the rest of the code run.
It’s not necessary that callback functions are only used with Asynchronous Javascript. It is used in both Synchronous and Asynchronous. Let’s see each in detail with examples.
Level up your skills and Join Developers Zone India Community
Callback Function with Synchronous Javascript.
In Synchronous Javascript, callback functions are mostly used in all inbuilt functions. All array functions in Javascript use callback. Let us see the Array. map function in Javascript.
In the above code, you can see Arr.map() is itself a function containing another Arrow Function as a parameter. Here Map function is acting as the Primary function and the Arrow function act as a callback.
Join Engineering Communities and Events related to your Career Path.

Callback Function with Asynchronous Javascript.
In Asynchronous Javascript, Code execution does not stop to wait for a function to get completed, it runs that function in the background and executes the rest of the code. See below
Join the dynamic Mumbai Tech Junction community
Output:
Data fetched from Array
[5,10,15,20,25,30,35,40,……….,5000]
As we see above code, despite of written on the second, Function B is getting executed before Function A, due to setInterval() function. This is the basic feature of Asynchronous Javascript, but what if the result of Function B is dependent on Function A? In such case, we can use Function B as a callback for Function A so that it gets executed only after Function A. See below How to give the callback.
Output:
[5,10,15,20,25,30,35,40,……….,5000]
Data Fetched from Array
Now we can see that Function B is executed later despite the Asynchronous run of Function A. This is how the callback function works. It is mostly used when you are fetching data from Database.
Join the Global Developers Zone community and code your way to success!
Conclusion
We have seen What are the Callback Function, and how it works in Synchronous and Asynchronous Javascript. We have seen examples of it. The callback is one of the very important concepts. of Javascript which is exclusively used.
Keep Coding!!
Deep dive into Engineering, Join millions like you
