Search code examples
node.jsparameterscallbackdefault

default parameters in node.js


How does one go about setting default parameters in node.js?

For instance, let's say I have a function that would normally look like this:

function(anInt, aString, cb, aBool=true){
   if(bool){...;}else{...;}
   cb();
}

To call it would look something like this:

function(1, 'no', function(){
  ...
}, false);

or:

function(2, 'yes', function(){
  ...
});

However, it doesn't seem that node.js supports default parameters in this manner. What is the best way to acomplish above?


Solution

  • Simplest solution is to say inside the function

    var variable1 = typeof variable1  !== 'undefined' ?  variable1  : default_value;
    

    So this way, if user did not supply variable1, you replace it with default value.

    In your case:

    function(anInt, aString, cb, aBool) {
      aBool = typeof aBool  !== 'undefined' ? aBool : true;
      if(bool){...;}else{...;}
      cb();
    }