Javascript Callback Functions (Very Simple Examples)

Welcome to a quick tutorial and examples of callback functions in Javascript. When some beginners hear the term “callback function”, they immediately foam in the mouth and start mumbling something about “very difficult”. Well, they are actually stupidly simple.

A callback function is a function that we pass into another function; The callback function is then called inside the “main function”.

  • function demoA () { console.log("FOO!"); }
  • function demoB (fn) { fn(); }
  • demoB(demoA);

Yep, that’s all to it. Callback functions are still “normal functions”, they are just being used in a so-called innovative way. No need to foam in the mouth, read on for more examples!

ⓘ I have included a zip file with all the example source code at the start of this tutorial, so you don’t have to copy-paste everything… Or if you just want to dive straight in.

 

 

QUICK SLIDES

 

TABLE OF CONTENTS

Download & Notes Callback Function Useful Bits & Links
The End

 

DOWNLOAD & NOTES

Firstly, here is the download link to the example code as promised.

 

QUICK NOTES

If you spot a bug, feel free to comment below. I try to answer short questions too, but it is one person versus the entire world… If you need answers urgently, please check out my list of websites to get help with programming.

 

EXAMPLE CODE DOWNLOAD

Click here to download the source code, I have released it under the MIT license, so feel free to build on top of it or use it in your own project.

 

 

CALLBACK FUNCTION EXAMPLES

All right, let us now get on with solving the mysteries of the callback function in Javascript – What it is, and how to use it.

 

EXAMPLE 1) CLASSIC CALLBACK EXAMPLE

1-classic.html
// (A) FUNCTION TO CALLBACK
function callback () {
  console.log("FOO!");
}

// (B) PASS CALLBACK() INTO SETTIMEOUT()
setTimeout(callback, 1000);

Callback functions are actually straightforward, and here is a classic example. As in the above introduction, there are 2 “conditions” that make a callback function.

  • When we pass a function into another function. Here, we pass callback() into setTimeout() as a parameter.
  • The callback function gets called inside the main function. Here, callback() will be called by setTimeout() after 1 second.

 

 

EXAMPLE 2) SIMPLE CALLBACK

2-simple.html
// (A) FUNCTIONS TO CALLBACK
function callbackA () {
  console.log("foo");
}
function callbackB () {
  console.log("bar");
}
 
// (B) THE "MAIN FUNCTION"
function main (callback) {
  console.log("Main");
  if (typeof callback == "function") { callback(); }
}
 
// (C) GO!
main(callbackA);
main(callbackB);

Let us now upgrade from “very simple example” to “simple example”. Here is what a “common callback” will actually look like.

  • We have 2 “callback functions” – function callbackA() and function callbackB().
  • A main() “main function” that accepts a function as a parameter.
  • So, very simply –
    • main(callbackA) will run main(), which then calls back to callbackA().
    • main(callbackB) will run main(), then calls back to callbackB().

 

 

EXAMPLE 3) CALLBACK WITH PARAMETERS

3-parameters.html
// (A) CALLBACK FUNCTIONS
// (A1) OUTPUT TO CONSOLE
function callbackA (res) {
  console.log(res);
}
// (A2) APPEND TO HTML BODY
function callbackB (res) {
  document.body.innerHTML = res;
}
 
// (B) "MAIN FUNCTION"
function main (name, callback) {
  var str = "My name is " + name;
  if (typeof callback == "function") { callback(str); }
}
 
// (C) GO!
window.addEventListener("load", () => {
  main("John Doe", callbackA);
  main("Jane Doe", callbackB);
});

Of course, callback functions are still functions, we can pass parameters around. This is an interesting and useful part about callback functions – Depending on which callback function we pass in, we can change how the “main function” processes the results.

  • If we pass callbackA() into main(), it will output the person’s name into the console.
  • But when we pass callbackB() into main(), it will insert the person’s name into the HTML page instead.

 

 

EXAMPLE 4) AJAX CALLS

Lastly, some of you sharp code ninjas should have realized. Can’t we just do the above in a “normal sequential order”?

var result = main("John");
callbackA(result);
result = main("Jane");
callbackB(result);

Wouldn’t that be the same, and in a much less confusing manner? What purpose do callback functions serve then? To answer that question, let’s take away “sequential” from the equation:

4-ajax.html
// (A) CALLBACK FUNCTIONS
// (A1) OUTPUT TO CONSOLE
function callbackA (res) {
  console.log(res);
}
// (A2) APPEND TO HTML BODY
function callbackB (res) {
  document.body.innerHTML = res;
}
 
// (B) "MAIN FUNCTION" - DOES MULTIPLE AJAX CALLS
function main (target) { for (let t of target) {
  fetch(t.url)
  .then((res) => { return res.text(); })
  .then((txt) => { t.callback(txt); });
}}
 
// (C) GO!
window.addEventListener("load", () => {
  main([
    { url: "dummyA.html", callback: callbackA },
    { url: "dummyB.html", callback: callbackB }
  ]);
});

This may be quite brutal for the total beginners, but what this essentially does is multiple AJAX (asynchronous) calls to the server. In parallel processing, we do not know which will end first – This is where callbacks make sense, whichever ends first runs the callback first. In a nutshell, this will be more efficient than doing “sequential one-by-one”.

 

USEFUL BITS & LINKS

That’s all for this guide, and here is a small section on some extras and links that may be useful to you.

 

LINKS & REFERENCES

 

INFOGRAPHIC CHEAT SHEET

Javascript Callback (Click to enlarge)

 

THE END

Thank you for reading, and we have come to the end of this guide. I hope that it has helped you with your project, and if you want to share anything with this guide, please feel free to comment below. Good luck and happy coding!

Leave a Comment

Your email address will not be published.