Here I understood what is Call back in JavaScript

kajathees prem
2 min readMar 7, 2021

As JavaScript developers we all would have studied callback function theoretically. But many of us don’t know how actually it works and don’t have a clear knowledge about callback function. I also was not clear about callback function until my lecturer explained well.

What is Callback?

In simple terms we can say that a function has to be executed after another function executed. That’s why we call this function as callback for a reason. Basically in JavaScript one function can pass another functions as an argument. That passing argument is the callback function.

Why we use Callback?

function callName1(){
console.log("john");
}
function callName2(){
console.log("peter");
}
callName1();
callName2();

In this above code, like you are expecting the callName1() function will be executed 1st and then callName2() will be executed next. But all codes won’t be like this. Some functions will be executed after the response came like API.

In the below example I am going to execute setTimeout() function to understand further.

function callName1(){
setTimeout (function(){
console.log("John");
},1000);
}
function callName2(){
console.log("peter");
}
callName1();
callName2();

now the output will be like below

//output
peter
John

Here also we called callName1() function 1st and then called callName2() function 2nd. but the output is vice versa. What happened was the 2nd function didn’t wait to execute the 1st function as 1st function will be executed after 1 second. So callback is a way to make sure that a particular code doesn’t execute until another code finished the execution.

Callback Creation

Here we will see how to create a callback function.

function carStage(car,callback){
alert('Starting my ${car}');
callback();
}
carStage('BMW',function(){
alert('${car} is stopped');
});

Here you can see that 2 alerts will be appeared like the 1st alert will be ‘Starting my BMW’ and the 2nd alert will be ‘BMW is stopped’. Here we have passed our callback function as an argument during carStage function.

Conclusion

I hope you have a basic idea of callback function. Still there are many things to learn about callbacks. We can learn those things by practicing day by day.

--

--