Quick Validating JavaScript Function Before Call

November 18, 2011 · 0 comments   175 views

in Technical Publications

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.)

  1. var doCallBackWhenDone = function (callback) {
  2.     if (workIsDone && (typeof callback === ‘function’)) {
  3.         callback();
  4.     }
  5. };

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

  1. var doCallBackWhenDone = function (callback) {
  2.     workIsDone && (typeof callback === ‘function’) && callback();
  3. };

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.

  1. var doCallBackWhenDone = function (callback) {
  2.     workIsDone && callback && callback();
  3. };

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

  1. var doCallBackWhenDone = function (callback) {
  2.     if (workIsDone) {
  3.         callback && callback();
  4.     }
  5. };

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.