What are Javascript Callbacks For a Newbie

So what are callbacks in Javascript?
Simply put, those are functions that passed over to other functions for the purpose of being called later on when. Functions in javascript are “first-class objects” that means they are just like Number, String, Arrays, Objects etc. You can create a variable and assign his value to a function like so:

var iAmAFunction = function() {    
  //code in function

// If you want to run this function you simply
// add parentheses to the variable name:


and now lets say we have a function that accepts a function (callback) will do something and then call the callback when done.
** I’ll start using the arrow shorthand for creating functions

const thisIsTheCallback = _ => console.log('thisIsTheCallback')

const funcWithCallback = (other, callback) => { 

As for the code above what will be the output of this snippet:

funcWithCallback('passedParam', thisIsTheCallback);
//output will be:
// "passedParamthisIsTheCallback"

we run the main function that logs “passedParam”then it calls our passed function the callback that it logs “thisIsTheCallback” Important to note that you are not forced to create a name function or set a function into a variable for passing it to another function as a callback.
You can always use anonymous function like so:

thisIsTheCallback(otherParam, function() {
  //this is the anonymous function
  //and it will be called inside "thisIsTheCallback"

So our passed function (the callback) will be passed for these scenarios:
  • in setTimeout or setInterval as you will want your callback to be called in X seconds or every X seconds.
  • when you have an ajax call and you will want your callback to be called with the ajax response as soon as the ajax response has arrived.
  • when loading a file on the server.
  • when some event has happened in the UI or on your code

Leave a Reply

Notify of