Sunday, June 2, 2024
109
rated 0 times [  113] [ 4]  / answers: 1 / hits: 40995  / 13 Years ago, wed, march 7, 2012, 12:00:00
// opt_options is optional
function foo(a, b, opt_options) {
// opt_c, opt_d, and opt_e are read from 'opt_options', only c and d have defaults
var opt_c = 'default_for_c';
var opt_d = 'default_for_d';
var opt_e; // e has no default

if (opt_options) {
opt_c = opt_options.c || opt_c;
opt_d = opt_options.d || opt_d;
opt_e = opt_options.e;
}
}


The above seems awfully verbose. What's a better way to handle argument options with default parameters?


More From » design-patterns

 Answers
28

Now that I think about it, I kind of like this:



function foo(a, b, opt_options) {
// Force opt_options to be an object
opt_options = opt_options || {};

// opt_c, opt_d, and opt_e are read from 'opt_options', only c and d have defaults
var opt_c = 'default_for_c' || opt_options.c;
var opt_d = 'default_for_d' || opt_options.d;
var opt_e = opt_options.e; // e has no default
}

[#87003] Tuesday, March 6, 2012, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
raymondorlandok

Total Points: 530
Total Questions: 110
Total Answers: 96

Location: Lebanon
Member since Wed, Dec 21, 2022
1 Year ago
;