hownowbrowncow
hownowbrowncow

Reputation: 475

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?

Upvotes: 30

Views: 40146

Answers (4)

mikemaccana
mikemaccana

Reputation: 123178

2017 answer: node 6 and above include ES6 default parameters

var sayMessage = function(message='This is a default message.') {
  console.log(message);
}

Upvotes: 81

serv-inc
serv-inc

Reputation: 38177

See the github issue. You can enable default parameters in current node versions (f.ex. 5.8.0) by using --harmony_default_parameters

node --harmony_default_parameters --eval "const t = function(i = 42) { return i }; console.log(t());"

[...]

It'll be enabled by default in v6.0

Upvotes: 3

Wex
Wex

Reputation: 15695

You can use bind to create a new function that already has a set of arguments passed into it:

fn1 = fn.bind(fn, 1, 'no', function(){}, false);
fn1();
fn2 = fn.bind(fn, 2, 'yes', function(){});
fn2(true);

Alternatively, langues like CoffeeScript that compile into JavaScript provide mechanisms that support default parameters without having to use bind:

CoffeeScript:

fn = (bar='foo') ->

JavaScript:

fn = function(bar) {
  if (bar == null) {
    bar = 'foo';
  }
};

Upvotes: 1

Zakkery
Zakkery

Reputation: 420

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();
}

Upvotes: 11

Related Questions