Quick Validating JavaScript Function Before Call

There are many instances where we have to execute a function where we have no idea whether it actually exists or not. Let’s say for example, a function expects another function passed to it as parameter, which would later be executed as callback. A very common usage would be the callback function sent to AJAX requests.

Generally, we would code it with an if-block and check whether the variable (say, callback) is a function or not. If it is, we execute it when we have the work completed (say marked by a variable called workIsDone.)

var doCallBackWhenDone = function (callback) {
    if (workIsDone && (typeof callback === 'function')) {
        callback();
    }
};

The above code can be re-written in a very simple fashion (though might confuse others reading the code.)

var doCallBackWhenDone = function (callback) {
    workIsDone && (typeof callback === 'function') && callback(); 
};

However, for all practical purposes for a loosely typed language such as JavaScript, we can avoid the specific type checking. And if your coding style is ‘duckish’, dropping strict type-checking is good in all ways.

var doCallBackWhenDone = function (callback) { 
    workIsDone && callback && callback(); 
};

In fact, if you have multiple things to do when workIsDone is true, you can write the code as:

var doCallBackWhenDone = function (callback) { 
    if (workIsDone) { 
        callback && callback(); 
    } 
};

Why it works?

JavaScript interpreter, while evaluating a Boolean expression, optimizes its execution-time by ignoring to execute the part of the expression whose result will not have an effect on the outcome of the expression. For example, if we do c && (a || b);, the resultant value will always be false if c is false. Thus, if c is found to be false, the rest of the expression is then not executed at all.

This trick can be applied anywhere (inside JavaScript that is!) and whole lot of code-blocks can be reduced and made to look sexier.

Leave a comment