Search code examples
javascriptfunction-parameter

Skipping optional function parameters in JavaScript


Could you please point me to the nice way of skipping optional parameters in JavaScript.

For example, I want to throw away all opt_ parameters here:

goog.net.XhrIo.send(url, opt_callback, opt_method, opt_content, {'Cache-Control': 'no-cache'}, opt_timeoutInterval)

Solution

  • Solution:

    goog.net.XhrIo.send(url, undefined, undefined, undefined, {'Cache-Control': 'no-cache'})
    

    You should use undefined instead of optional parameter you want to skip, because this 100% simulates the default value for optional parameters in JavaScript.

    Small example:

    myfunc(param);
    
    //is equivalent to
    
    myfunc(param, undefined, undefined, undefined);
    

    Strong recommendation: use JSON if you have a lot of parameters, and you can have optional parameters in the middle of the parameters list. Look how this is done in jQuery.