MDN Defination: A callback function is a function passed into another function as an argument, which is then invoked inside the outer function to complete some kind of routine or action.
When you are in a problem and something comes to you as a solution it always remains in our mind.
So today I will also make you fall into a problem and then give you a solution to come out of it.
"Now get ready to fall into a problem !!!!. HAHAHAHAHAHA"
As of now, you have fallen into the problem and now might be thinking of the solution to overcome it.
So let me make you understand the problem more in details.
When the code execution starts, on reaching to the Line 28 it calls the function printLatestFriendsCount, which internally calls fetchFrndsCountFromServer on Line 15.
Moving to Line 18, "Friends Count - undefined" is printed.
"Seeing the problem stated above does some solution strikes your mind?"
Ok, let me give you a hint, remember this "Hey, I am busy for 1000 ms, once I am free I will do whatever written in my function body, therefore you can move on" ?, It says when it's free it will run whatever written in it's function body so what if we can put our next function calls inside it's function body.
So it's like telling - "Hey man, please callback me once you are done with your work". Ya, you cought it correct, the concept of callback came like this only. So talking technically, we ask a function(Higher Order Function) to call our function passed as paramater to it, once it's done with its work.
Let's see how we can solve the above mentioned problem using the concept learned above.
"Don't you think it's a simple solution to a complex problem"
Yes, really it's like passing a parameter to a function and doing a normal function call.
Let's dive deep into the solution and understand it more in details.
When cursor interacts setTimeout on Line 10, it just instructs it that - "do run code in your function body once you are free(after 1000ms/1 sec)".
After this, the program cursor moves to Line 23 and "program run" get's over.
But the function call of setTimout is still pending, once 1000ms/1 sec is over the function declared on Line 10 as a parameter to setTimout get called, which internally call's the function definition inside the callbackFn variable and also pass a value(assuming returned from the server) 87 to the function.
callbackFn being called cursor now moves to function definition on Line 18 and the passed "87" value is received in the latestCount variable. moving on to Line 19 our local friends count variable frndsCount is updated and then finally the Line 20 executes which print's - "Friend's Count - 87".
"Yepiee!!!, we finally solved the problem :), But wait did you notice something? on Line 10, the first parameter of setTimeout is also a callback function, if you understood how then comment on this post and if couldn't understand then also feel free reach me"