JavaScript callback functions

Another primer, this time on callback functions.  Call back functions are basically a function that is passed as an argument, or included wholly as in the case of anonymous functions, in another function’s call. It hails from, wait for it… functional programming.

One way of understanding how callbacks function *pardon the pun*, is based on one form of creating a function in JavaScript:

var someFunction = function functionName() {  // code goes here}

This is known as a function expression, whereby a function is declared and assigned to a variable. [1] Now, someFunction can be used to invoke functionName() just by calling it similarly to how a function would be called i.e. someFunction();

In a callback function pattern, in one scenario, a named function which has already been declared is passed as an argument in another function.

function gradeBoost(x){ // call back function
   return x += (x *= .15);
}

function bonusQuestion(receivedMarks, callback){ // uses callback function
  return callback(receivedMarks);
}

var finalMarks = bonusQuestion(45, gradeBoost));
console.log(finalMarks);

So, in the example above, gradeBoost is the callback function. In bonusQuestion, the second argument ‘callback’ is set to receive (be assigned) the callback function, gradeBoost, similar to the first code explanation block above this example.

Within the body of bonusQuestion, the assigned function is setup based on the parameter list of the gradeBoost callback function. The result being when bonusQuestion is called and passed in gradeBoost as the callback function argument, gradeBoost returns the result of the calculation to the bonusQuestion function call.

This is in essence how callbacks are cast and called. For some more applications of callback functions see the post on Asynchronous JavaScript.

Leave a Reply

Your email address will not be published. Required fields are marked *