Self Documenting Flexible Parameters

on in JavaScript Arrays & Objects
Last modified on

When managing function parameters, it’s often more maintainable to use an options object. This allows you to pass a single object with various properties instead of a long list of parameters.

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 of 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
}

Use the JavaScript Options Object:

function my_function(options) {
    // Default values
    const defaults = {
        param1: false,
        param2: null,
        param3: '',
        param4: function(a, b) {
            return a < b;
        },
        param5: null
    };

    // Merge defaults with user-provided options
    const settings = Object.assign({}, defaults, options);

    // Access settings like settings.param1, settings.param2, etc.
    // More code here
}
  • Defaults Object: The defaults object holds the default values for all parameters.
  • Object.assign(): This method merges the defaults object with the options object passed to the function. Any properties in options will override the corresponding properties in defaults.
  • Single Parameter: The function now takes only one parameter — a configuration object — making it easier to add or remove options without affecting other parts of the code.
my_function({
    param2: "param2 value",
    param3: "param3 value"
});

Related posts