Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 221
hownowbrowncow Avatar asked Feb 17 '16 17:02

hownowbrowncow


People also ask

What are default parameters in JS?

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.

What are the parameters that are default values?

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.

What is default parameter example?

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.

How do you set a default parameter?

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 .


Video Answer


2 Answers

2017 answer: node 6 and above include ES6 default parameters

var sayMessage = function(message='This is a default message.') {   console.log(message); } 
like image 133
mikemaccana Avatar answered Oct 07 '22 12:10

mikemaccana


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(); } 
like image 24
Zakkery Avatar answered Oct 07 '22 12:10

Zakkery