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?
Default parameter in Javascript The default parameter is a way to set default values for function parameters a value is no passed in (ie. it is undefined ). In a function, Ii a parameter is not provided, then its value becomes undefined . In this case, the default value that we specify is applied by the compiler.
A parameter with a default value, is often known as an "optional parameter". From the example above, country is an optional parameter and "Norway" is the default value.
Default arguments are overwritten when the calling function provides values for them. For example, calling the function sum(10, 15, 25, 30) overwrites the values of z and w to 25 and 30 respectively.
In JavaScript, function parameters default to undefined . However, it's often useful to set a different default value. This is where default parameters can help. In the past, the general strategy for setting defaults was to test parameter values in the function body and assign a value if they are undefined .
2017 answer: node 6 and above include ES6 default parameters
var sayMessage = function(message='This is a default message.') { console.log(message); }
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(); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With