How does a callback function work?
An Example :
Here, we have a function fooGreeting which takes a string as a argument, and then alerts the message with the argument concatenated to it.
Then we have another function defined as fooInput which takes callback as an argument
Is it a pattern?
It is a Observer pattern. You can think of it as a Publish/Subscribe model. And is easy to implement in "any" programming language.
Why use callBack Function?
Callback function are generally used when we are getting a response from the api and need to excute a function when we have the response set or it is received
we make a request to a server. After 5 seconds the response is modified and our callback function
Results gets executed.
Where can we use callBack Functions?
Callbacks are used for asynchronous operations like – making an request to the Google Maps, fetching/writing data from/into a file, registering event listeners etc. All these use callbacks. This way once the data/error from the operation is returned, the callbacks are used to do something with that inside our code.
Multiple Callback Functions Allowed?
Yes, we can pass more then one callback functions as arguement
How will Callback functions Help?
They will allow you to
1. DRY - Do not Repeat Yourself
2. To maintain generic functions
3. To write more specialized functions
4. Easy debug as the code is more readable