2

What is the purpose of the above line of code. I'm specifically confused by OR-ing the 'function() {}'. Why the empty function? To give a little more context to the line of code, here is the more complete function definition.

this.detectQRCode = function(imageData, callback) {

     callback = callback || function() {};

     client.decode(imageData, function(result) {
       if(result !== undefined) {
         self.currentUrl = result;
       }
       callback(result);
     });
};
3
  • This is the same as if (!callback) callback = function() {};. I.e. it defines fallback value
    – hindmost
    May 13, 2015 at 16:29
  • It means if callback function exists then execute that callback or simply do nothing by executing exmpty function...
    – Rayon
    May 13, 2015 at 16:30
  • If no callback assign function() {} so that the later execution of callback doesn't throw error
    – kidwon
    May 13, 2015 at 16:32

1 Answer 1

0

It is just a "short circuit" coding style. It is checking to ensure that callback isn't undefined. If it is undefined, then it is assigning it an anonymous function in order for the callback() code to not fail.

It is equivalent to

if(typeof(callback) == "undefined") callback = function(){};

A pitfall of this approach is that if callback is defined, but is not a function, then using callback() on something which cannot be called will cause an error. It would be best to use

if(toString.call(callback) != "[object Function]") callback = function(){};

Not the answer you're looking for? Browse other questions tagged or ask your own question.