// 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?
Design patterns are reusable solutions to commonly occurring problems in software design. They are proven solutions, easily reusable and expressive. They lower the size of your codebase, prevent future refactoring, and make your code easier to understand by other developers.
In JavaScript, a parameter has a default value of undefined. It means that if you don't pass the arguments into the function, its parameters will have the default values of undefined .
Anyways, the default value of a variable in JavaScript is null or undefined .
An options object is an object passed into a method (usually a method that builds a jQuery widget, or similar) which provides configuration info.
This uses jQuery.extend but could be interchanged with an object merger from your library of choice or Object.assign in ES6.
function Module(options){ var defaults = { color: 'red' }; var actual = $.extend({}, defaults, options || {}); console.info( actual.color ); } var a = new Module(); // Red var b = new Module( { color: 'blue' } ); // Blue
Edit: Now also in underscore
or lodash
!
function Module(options){ var actual = _.defaults(options || {}, { color: 'red' }); console.info( actual.color ); } var a = new Module(); // Red var b = new Module( { color: 'blue' } ); // Blue
In Javascript ES6 you can use Object.assign:
function Module(options = {}){ let defaults = { color: 'red' }; let actual = Object.assign({}, defaults, options); console.info( actual.color ); }
Using the ES2018 spread syntax for object properties:
const defaults = { a: 1, b: 2 }; const ƒ = (given = {}) => { const options = { ...defaults, ...given }; console.log(options); };
Using ES6/ES2015 features, several more options are available.
Using destructuring assignment:
const { a = 1, b = 2 } = options;
You can also use destructuring function parameters:
const ƒ = ({a = 1, b = 2, c = 3} = {}) => { console.log({ a, b, c }); };
Using Object.assign
:
options = Object.assign({}, defaults, options);
No dependencies!
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