Callback Function in Javascript

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.

Learn the concepts of Javascript with YourEngineer

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.

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.

				
					//Map Function in Javascript

let Arr = [24,27,98,87,54]
let mappedArray = Arr.map(ele => { return ele })



				
			

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.

Learn the concepts of Javascript with YourEngineer

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

				
					//Asynchronous Javascript 

//Function A
arr = [1,2,3,4,5,6,7.......,1000] //Array of length 1000
 function printData(){
    newArray = []
    for(let i = 0; i < arr.length; i++){
        ele = arr[i]*5
        newArray.push(ele)
    }
    console.log(newArray)
}
//Funtion B
let finalResult = function (){
    console.log("Data fetched from Array")
}

setInterval(printData,5000) //printData function will take 5 seconds to execute
finalResult()

				
			

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.

				
					//Asynchronous Javascript 

//Function A
arr = [1,2,3,4,5,6,7.......,1000] //Array of length 1000
 function printData(callback){
    newArray = []
    for(let i = 0; i < arr.length; i++){
        ele = arr[i]*5
        newArray.push(ele)
    }
    console.log(newArray)
    callback() //writing a callback function to execute at last
}
//Funtion B
let finalResult = function (){
    console.log("Data fetched from Array")
}

setInterval(printData(finalResult),5000)
//finalResult function will be passed as the parameter and will act as 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.

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!!

What is YourEngineer?

YourEngineer is the first Engineering Community Worldwide that focuses on spreading Awareness, providing Collaboration and building a focused Career Approach for Engineering Students.

Deep dive into upskilling with Javascript
Join millions like you

campus cover
  • Create an Account and Earn 1000 Coins
  • Pass a Quiz and Earn 20 Coins
  • Earn 10 Coins for Daily Visit 
  • Earn 50 Coins for invite someone to join a group
  • Earn 100 Coins for finishing a course

India's Largest Engineering Event

technX

28th November 2022 - 4th December 2022