FLASH SALE Get 20% OFF everything using the coupon code: FLASH20 View WordPress Plugins →

Self Documenting Flexible Parameters

on in jQuery
Last modified on

Changing the number of JavaScript function parameters can be unproductive because of the need to update other code calling that function whose parameters are changed. Greater chaos could occur if the work is done in teams. Addition or reduction of the number of JavaScript function parameters must be communicated properly to prevent chaos. Updating code to adapt the API changes takes time and decreases productivity.

So what is the solution to this problem? The solution is obviously to never add and reduce the number JavaScript function parameters, especially those functions decided as public interface.

So instead of doing this to define a public function:

function my_function(param1, param2, param3, param4, param5) {
    // More code here
}

utilize the JavaScript object syntax and jQuery.extend():

function my_function(params) {
    params = $.extend(true, {}, {
        param1: false,
        param2: null,
        param3: '',
        param4: function(a, b) {
            return (a < b);
        },
        param5: null
    }, params);

    // More code here
}

Keep the number of parameter to one, that is the JavaScript object containing attributes replacing function parameters. Although we change the parameters of the function with the object syntax, function interface remains easy to understand, thanks to jQuery.extend(). In fact, we get added value with the ability to provide a default value and data type hint. The attributes whose values are the same with their defaults, don’t need to be passed to the function call. We just need to call the function as in the example below, which param1, param4, and param5 have the same values with their defaults:

my_function({
    param2: "param2 value",
    param3: "param3 value"
});

Related posts