TzookB

What are Javascript Callbacks For a Newbie

Mon Dec 31 2018
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:
  iAmAFunction();

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

const funcWithCallback = (other, callback) => { 
  console.log(other);
  callback();
}

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

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

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