JavaScript Callback, the real deal!

Let’s begin with an Example

If you claim to know basic JavaScript, even client-side, you must have at some point used callback. Surprised? Well, recollect the setTimeout and setInterval functions.

setTimeout(function(){ alert("Hey there!") }, 1000);

In the above code, you will find that the alert statement is passed as a function that gets executed after 1000 milliseconds. This is callback!

Explanation

What occurred in the example above is your piece of code that is passed as a function definition is actually executed by the setTimeout function at some point in its sequence of operations. In other words, your function is called back from within the setTimeout function.

You may typically find that the callback is usually executed as the last statement, but it does not have to be that way. So, do not misunderstand callback to be some fancy equivalent or replacement of return statement within a function. Let’s take that with another example.


var double = function(n) {
return (n + n);
};
function someCalculation(a) {
// ... some calculations
var ans = (a * a) / double(a);
return ans;
}
// call these 2 functions:
var result = someCalculation(5);
console.log(result);

This is a classic example where each function returns a value that is used in subsequent computation or programing logic. Let’s re-implement the same functions as callback and see the difference.


function someCalculation(a, callback) {
// ... some calculations
var calc = (a * a);
callback(calc);
}
var double = function(n) {
var result = n / (n + n);
console.log(result);
};
// call the function with callback function definition
someCalculation(5, double);

// .. this could also be implemented as:
someCalculation(5, function(n){
var result = n / (n + n);
console.log(result);
});

In this implementation, the function double is passed as an argument directly into the someCalculation function.

The former example makes code modular, while the later example with callbacks makes it functional where the result of a certain function is passed to the subsequent control structure (function). If someCalculation in the function above was an API provided via some library, you as the developer of your code, can pass your function as another parameter to the API function and control the execution of your logic.

When should you use Callback

Javascript provides many Asynchronous APIs. The most common one that is used in developing modern web applications is XHR or AJAX. Other providers such as MongoDB, NodeJS, JQuery, Angular, etc. provide Asynchronous APIs. While the asynchronous APIs allow browsers to build different parts of a page in parallel, a developer often needs to control or work on the results of the APIs. This is where callback comes in very handy. Callback allows developer functions to be passed as parameters to APIs (which, actually most JavaScript APIs expect anyways!) and control the application logic. Let’s take that with a JQuery example.

jQuery is a fast, small, and feature-rich JavaScript library. It makes things like HTML document traversal and manipulation, event handling, animation, and Ajax much simpler with an easy-to-use API that works across a multitude of browsers. With a combination of versatility and extensibility, jQuery has changed the way that millions of people write JavaScript.”
https://jquery.com


var hidden = false;
$("#divElement").slideDown( "slow", function() {
// your code when animation completes, such as:
$("#divElement).hide(function(){
hidden = true;
}
);
}
);

In this example, the JQuery-provided slideDown function takes callback function that allows execution additional logic. Even the further logic could call additional APIs where further callback functions can be passed.

Conclusion

JavaScript callbacks is a great capability that allows more asynchronous functions / APIs to be used without jeopardizing developers control over the execution logic. There is a lot of material and instruction videos to dive deep into this topic, so the goal of this blog was to introduce this concept without a lot of technical jargons and allowing you to learn by observation from the examples provided.

Please comment or provide feedback if anything obvious was missed or any additional perspective needs to be covered.

Javascript Functions as Javascript Variables

Function Basics. Level Set!

If you are coming from a programming background, you all know what declaring a function means, right? It looks something like this in javascript. Some programming languages enforce specifying a return type. Javascript does not, but let’s keep that discussion for some other time.

function add(x,y) {
return x+y;
}

Having declared a function just makes it available for use in your program. It does not execute it right away (of course!) In order to execute the function in Javascript, we drop the keyword “function” and pass actual values within the parentheses, such as shown below.

add(3,4)
RESULT:
7

Instead of declaring and executing the functions in 2 different steps, Javascript also provides an approach to declare and execute the function immediately. This is also called as IIFE (stands for: Immediately-invoked function expression). An example is shown below.

(
function add(x,y) {
alert(x+y);
}
) ();

In this example, please look at specifically how parentheses are used. Note: Semi-colon is not mandatory in Javascript, but is usually a good practice to separate blocks of code.

Here Comes the VARIABLE Part

Let’s start with an example to explain this.

var add = function(x,y) {
return x+y;
}

This is a valid declaration of a function in Javascript, rather a powerful one (I think). It is not only declaring the function, but also storing the declaration in the variable named add. This is close to storing the result of an expression in a variable, except for the difference that the expression is evaluated (executed) and the result is stored in the variable versus in this case, the function is not executed to store the result in the variable. Thus, the variable is now the function declaration and therefore, the following call will still provide the same result as it did in the earlier declaration. Test this code out in your browser console window. (TIP: If you are using chrome browser, click Ctrl+Shift+i and find your console window, usually in the bottom half. You may simply copy/paste each line one by one. This way you don’t have to write an entire Javascript file for this quick test ).

function add(x,y){console.log("ADD:" + (x+y) )};
var sum = function(x,y){console.log("SUM:" + (x+y) )};
add(3,4); sum(3,4);
RESULT: (In your console window)
ADD: 7
SUM: 7

So, where does this lead to?

It leads to an important concept that makes Javascript very powerful. My opinion is that this is important to understand another very important feature in Javascript called as callback.

We will try to end this blog with an example that would allow you to look forward into callbacks.

Last Step. Passing Functions as Parameters to Another Function

Now that we have established that a function can be stored in (actually, assigned to) a variable, these variables can be passed as parameters to another function. Thus, instead of executing the function and passing the result as a parameter to the function, the entire function declaration can be passed as a parameter. This is huge! isn’t it? Maybe an example will make it more convincing. So here we go.

  var A = function() {
    console.log(“I am A");
  };
  var B = function(a) {  // ‘a’ is function declaration passed to ‘B'
    console.log(“I am B”);
    a(); // note we are actually executing the function ‘a' here
  }
// Now let’s call function B here which takes declaration of function A as the parameter
B(A);

RESULT: (In your console window) I am B I am A

If you have used Javascript to a certain extent, especially for creating client side events such as timeout or intervals, notice that you are already passing a function to the setTimeout and setInterval Javascript functions. Check out this example. There are two implementations of setTimeout but both essentially provide the same result.

/* *************************************************
   setTimeout has 2 parameters, 
   1. a function to doSomething
   2. timeout value in milliseconds
************************************************* */
// This will write to console after 1 second
  setTimeout( function() {
    console.log(“Timed out from setTimeout”);
  }, 1000 );

       var doSomething = function() {
          console.log(“Timed out from function write");
       };

// This also writes to console after 1 second
// Function write is passed to setTimeout function 
  setTimeout(doSomething, 1000);

Looking Ahead Into Callback

As mentioned half way in the blog, this powerful concept of declaring functions and assigning them to variables sets foundation for another powerful concept called Callback. So I’d like to conclude this blog by summarizing the concept and then providing an example by putting this together in a small application logging utility (which you can build upon for use in your application).

Summary

A function is just a declaration until it is explicitly evaluated. The declaration can be assigned to a variable, which can then be passed as a parameter to another function.

Thus, a Javascript Function is a Javascript Variable until it is executed (evaluated).

Example: Logging Utility

   var writeLog = function( txt, format) {
       console.log( format(txt) );
   };

var formatErr = function(text) { return "[E]" + new Date() + ":" + text; };
var formatWarn = function(text) { return "[W]" + new Date() + ":" + text; };

if(errorOccured) {
  var errText = "Error occurred. Terminating.";
  writeLog(errtext, formatErr);
} else {
  var warnText = "Warning occurred. Continuing.";   
   writeLog(warntext, formatWarn);
}


Do you have anything to add? Please feel free to express your point of view, provide examples and/or ask questions.