Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript callbacks and optional params

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?

like image 866
rvk Avatar asked Feb 27 '11 20:02

rvk


2 Answers

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 () { /* ... */ });
like image 107
Bergius Avatar answered Oct 05 '22 14:10

Bergius


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() {});
like image 40
Wayne Avatar answered Oct 05 '22 14:10

Wayne