Here I understood what is Call back in JavaScript

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?

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

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

--

--

Undergradute

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store