Show Buttons
Share On Facebook
Share On Twitter
Share On Google Plus
Share On Linkdin
Share On Reddit
Share On Stumbleupon
Contact us
Hide Buttons

Understanding callbacks in javascript

Ever won­der how call­backs work? Or how you could cre­ate your own? Call­backs have been around since a very long time and even though exces­sive use of call­backs can cause a lot of pain and con­fu­sion, call­backs are here to stay. In fact, even code that helps you avoid using call­backs uses call­backs internally(e.g. promises). In this arti­cle, I will use sim­ple exam­ples and a visu­al­iza­tions to demon­strate how you can use call­backs so that you can cre­ate your own when needed.


Call­backs are noth­ing but ordi­nary func­tions in javascript. This means that you can

  • Pass func­tions as an argu­ment to the other func­tions, just like you pass variables.
  • Return func­tions from other functions

A Sim­ple Example

Lets take a watered down exam­ple of jQuery’s ajax method. Below is the skele­ton code of its implementation.

In the above exam­ple, the sec­ond argu­ment to the get func­tion expects a func­tion as the argu­ment. We called it callback because it makes it eas­ier to under­stand, and because its a good con­ven­tion to have.

Here’s how you would use the get function.

Now lets try to visu­al­ize how this works.

Callbacks

There are few key points to understand

  • In the imple­men­ta­tion of get func­tion, the call­back is actu­ally a ref­er­ence to the anony­mous func­tion passed to it in the usage of get. Why? Because remem­ber we said ear­lier that a func­tion is just like a vari­able and can be passed to other functions.

  • In the imple­men­ta­tion of the get func­tion, when you invoke the call­back with response.data, you are invok­ing that anony­mous func­tion with an argument.

Con­grat­u­la­tions, you have now under­stood one of the key con­cepts in javascript!


Exer­cise

Per­haps you’d like to learn more about the actual imple­men­ta­tion of jQuery’s get func­tion. There’s a nice lit­tle source code browser for jQuery by James Padolsey. Take a look at the imple­men­ta­tion of the get func­tion there.

jQuery get source