Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
0
rated 0 times [  3] [ 3]  / answers: 1 / hits: 73176  / 10 Years ago, sat, may 10, 2014, 12:00:00

What is the best way to create a function that takes optional arguments in nodejs?



for example I know this method:-



    function optionalArguments(a,b){
var a = a || nothing;
var b = b || nothing;
}


but in this case if I do this :



optionalArguments(false,false)



both a and b return nothing although I have passed an argument.



and also I get unexpected token error when I call the function like this :



optionalArguments(,xxx);



Is there a better or a standard method to tackle optional arguments in nodejs?



Any help is appreciated.
Thanks in advance.


More From » node.js

 Answers
3

You do that exactly like for client side javascript.



The way you suggest does work but is, as you noticed, painful when the arguments that can be omitted aren't the last ones.



In that case, what's commonly used is an options object :



function optionalArguments(options){
var a = options.a || nothing;
var b = options.b || nothing;
}


Note that || is dangerous. If you want to be able to set arguments like false, , 0, NaN, null, you have to do it like this :



function optionalArguments(options){
var a = options.a !== undefined ? options.a : nothing;
var b = options.b !== undefined ? options.b : nothing;
}


A utility function can be handy if you do this a lot :



function opt(options, name, default){
return options && options[name]!==undefined ? options[name] : default;
}

function optionalArguments(options){
var a = opt(options, 'a', nothing);
var b = opt(options, 'b', nothing);
}


This way you can even call your function with



optionalArguments();

[#71100] Thursday, May 8, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
longd

Total Points: 616
Total Questions: 110
Total Answers: 101

Location: Andorra
Member since Sat, May 27, 2023
1 Year ago
;