JavaScript Callback Functions
In JavaScript, features are objects. Because of this, functions can be taken as arguments, and can be returned by means of other functions. Functions that do that are referred to as higher-order features.
How does a callback function work?
An Example :
function fooGreeting(name) { fooInput(fooGreeting);
|
Here, we have a function fooGreeting which takes a string as a argument, and then alerts the message with the argument concatenated to it.
fooGreeting(Harsh)
"Hello Harsh"
|
Then we have another function defined as fooInput which takes callback as an argument
fooInput(fooGreeting) |
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
function Req(query, callback){ Req("Server has send the", Results); |
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
function successCb() { |
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
Conculsion
JavaScript callback functions are amazing to use as they give extraordinary advantages to web applications and to your code. You should utilize them when the need comes , consistently search for approaches to refactor your code for Readability, Abstraction and Maintainability with callback functions.
I find it useful as it is to the point information, The example used are easy to understand. Thanks for sharing. Looking forward for more such articles.
Leave a Reply