Dublin, Ireland

All Content Copyright ©2019

Self Documenting Flexible Parameters

Changing the number of JavaScript function parameters can be unproductive because of the need to update other code calling that function whose parameters is 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 parameter! 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:

    param2: "param2 value",
    param3: "param3 value"

Find more JavaScript tutorials, code snippets and samples here or more jQuery tutorials, code snippets and samples here.

Find more JavaScript tutorials, code snippets and samples here or more jQuery tutorials, code snippets and samples here.

Added by Ciprian on Friday, January 12, 2018 in Blog, JavaScript

Do you want better SEO? More traffic? More conversions? More growth? We help companies exponentially grow their traffic and conversions, while outranking their competitors. With more than 10 years of experience, we’ve learned what is valuable to our clients.
SEO Dublin | SEO Malta

My Battle Tested Recommendations


Disclaimer: These recommendations contain affiliate links.

Privacy Policy