Javascript Functions and optional arguments

all parameters in javascript are optional, you can use the parameters array inside of a function to access parameters passed ordinally like so:

function myFunction(option1)
{
   var option2 = arguments[1];
   if(arguments[0] == option1)
      alert("Happy Day, Option1 = " + option1 + ", Option2 = " + option2);
}

myFunction("Hello", "World");

Produces: Happy Day, Option1 = Hello, Option2 = World

Hopefully this illustrates how you can use the arguments array to improve some code.

    function process_type(url, domid, domain, scan_id)
    {
            var myOptions = {
               domain: domain,
               scan_id: scan_id
            };

            if(arguments[4])
                myOptions["type"] = arguments[4];

            $.get(url, myOptions,

            function(data)
            {
                    $(domid).html(data);
            });
    }

Then you can call it with the last parameter being the type as optional, if the parameter is passed it is used if not it is omitted.

Also since the actual parameter is optional in the first place you can also add the name to the end of the function definition and use the same if but instead of arguments[4] you’d do if(type) myOptions["type"] = type;

    function process_type(url, domid, domain, scan_id, type)
    {
            var myOptions = {
               domain: domain,
               scan_id: scan_id
            };

            if(type)
                myOptions["type"] = type;

            $.get(url, myOptions,

            function(data)
            {
                    $(domid).html(data);
            });
    }

This Call would include type

 process_type("xxx", "xxx", "xxx", "xxx", "xxx");

where this call would not

 process_type("xxx", "xxx", "xxx", "xxx");

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)