If I am creating a function that takes in two mandatory parameters, one is a call back, and a couple optional how can I code it so that when I call it with only the 2 mandatory parameters it works.
Ex:
function save(color, size, weight, callback) { ... }
Where color and callback are mandatory and size and weight are optional. So if someone wants to call this function with only color and callback...
save('blue', function(...) { ... }) { ... }
save('blue', 56, function(...) { ... }) { ... }
But this assigns the callback function to size and weight, how can I fix this to do what I want?
A parameter object solves your problem nicely, like so:
function save(params, callback) {
params.color = params.color || 'default';
params.size = params.size || 0;
params.weight = params.weight || 0;
// ...
if (callback instanceof Function) { callback(); }
}
Use like this:
save({ color: 'blue', weight: 100 }, function () { /* ... */ });
JavaScript arguments must be aligned to the expected parameters positionally, so leaving out an argument in between others that are passed isn't going to work. One option is to pass optional arguments in a single object.
// callback is required
// additional arguments are passed as props of 'options'
function save(options, callback) {
var color = options.color || 'blue';
var size = options.size || 72;
}
Pass them like this:
save({ color: 'red' }, function() {});
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