Callback function are almost everywhere and play very important role in javaScript. Before jumping directly into the story, let’s clear the dust and understand “What is callback function?” and “Why callback function is important?” If not interested in basic, jump directly to the story.
What is callback function?
JavaScript code is executed line by line, but next line of code may run even if the effect is not finished. This can cause an error. We use callback functions to prevent this error.
Callback functions are executed asynchronously; or run at a specific time or event given in the code.
Callback function empowers the functional programming, instead of executing code from top to bottom; it executes function asynchronously.
Basic example of callback function
Since javaScript functions are first-class object, you can pass a function as variable to another function. A callback function is passed as parameter to another function, and callback function is run inside of the function; it was passed.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
function func1(x) {alert(x);} //If you run this function func1(3), it will alert 3 function func2(x) {alert(x);} //If you run this function func2(3), it will also alert 3 function func3(var1, var2, callback1, callback2) { Callback1(var1); Callback2(var2); //you can use these callback functions as per required flow of execution. } Func3(3,6,func1(), func2()) |
Callback function for DOM manipulation
A typical and basic use of callback function is; in a table row at last there is a column with name “Actions” that have td with two options “Accept” and “Reject”
Now, when user clicks on Reject button, it should ask “Do you really want to reject user ‘user_name’” If user click on “Yes” it should remove the row else no action is required just close the modal pop up. Means, we have to handle the code execution as per event.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
$('.reject').on('click', function(callback){ _this = $(this); (function callback(){ $('reject .primary').on('click', function(){ $('#modalReject').closeModal(); _this.parents('tr').fadeOut(); Materialize.toast('User request is rejected', 4000, 'information'); }); })(); $('.reject .secondary').on('click', function(){ $('#modalReject').closeModal(); }); }); |
Now, let’s make this abstract concept easy to understand – with an analogy of callback function / King and his spy.
King and his spy – JavaScript callback function
A king has to attack on a neighbor to rule on that state. He needs spy to get the insight of enemy’s strength. Here spy is a callback function who works for the king. The king can use any of his spy make them work.
King first sent his spy to know how many warriors are there in the enemy’s kingdom. If enemy’s kingdom has less than 10000 warriors; only then king will attack.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
function spy1(warriors){ if(warriors > 10000){ console.log('Total number of warriors' + warriors + '-' + 'Hold'); } else { console.log('Total number of warriors' + warriors + '-' + 'Attack'); } } function shouldKingAttack(totalWarrriors, callback){ callback(totalWarrriors); } shouldKingAttack(12090, spy1); shouldKingAttack(980, spy1); |
How spy or callback function is working?
Any function that is inside other function (directly or as an argument) is a callback function; to make this concept more easy call all the inside functions spy who is working for his king.
Now, spy has done his work, It’s only 980 warriors in the enemy’s kingdom. It’s time to attack on enemy.
King can have more than one spy to make work.
Enemy’s fort has 4 main gates and king has asked his spy to get the sense; “which gate is safe to attack?” But spy may cheat or get influenced by enemy that results wrong information.
So, king decided to send three different spies for the same task. Now, while making decision he evaluates the information and attack only if information from all 3 spies is same.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
function spy1(){ // huge processing required to get this data. return 2; } function spy2(){ // huge processing required to get this data. return 2; } function spy3(){ // huge processing required to get this data. return 2; } function whichGate(callback1, callback2, callback3){ var data1 = callback1(); var data2 = callback2(); var data3 = callback3(); if(data1 === data2 && data1 === data3){ console.log("Attack"); } else { console.log("Hold there is some problem"); } } whichGate(spy1, spy2, spy3); |
One king (main function), who passes the order to spies (callback functions) to do some task. All the spies do their work as per directed by the king. They cannot make any decision by themselves. They only do whatever has been ordered by King. For safer side, before making any big decision; king is comparing the information passed by different spies.
Conclusion
A main function (King) can have multiple callback functions (spy) to get work done. This way, main function can control the flow of execution by giving the right instructions to callback function. So, from now onwards consider all the callback functions as your worker who is always ready to do the tasks which you have ordered.