Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Javascript doesn't directly support this syntax (named parameters, specifically), so you'll have to resort to some sort of workaround. There are two approaches that work in certain situations:</p> <ol> <li><p>If you only need certain contiguous subsets of the parameters supplied, you can just declare them in order and then manually check whether the remaining parameters have been supplied. Javascript lets you call a function with less than the number of declared parameters, with the unpassed ones defaulting to <code>undefined</code>. Hence you could do something like this:</p> <pre><code>function myFunc(prm3 ,prm1, prm1) { // Use defaults if not supplied if (typeOf(prm1) == 'undefined') prm1 = 'value1'; if (typeOf(prm2) == 'undefined') prm2 = 'value2'; // Rest of function as normal ... }; </code></pre></li> <li><p>Alternatively, if you need more flexibility (i.e. either <code>prm3</code> or <code>prm2</code> could be supplied on their own, you'll need some way of associating a name with the value. Hence you'd have to pass all parameters in as an associate array, which is javascript is simply an object:</p> <pre><code>function myFunc(prms) { // Unpack actual arguments - if not supplied, will be 'undefined' var prm1 = prms.prm1; var prm2 = prms.prm2; var prm3 = prms.prm3; // Rest of function as normal ... }; // Call this function something like the following: myFunc({prm1: 'Hello', prm3: 'World'}); </code></pre></li> </ol> <p>Now both of these approaches have disavantages, but if you <em>need</em> to support optional arguments they're the only ways I'm aware of to do it.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload