undefined being treated as a missing optional argument

Allen Wirfs-Brock allen at wirfs-brock.com
Fri Apr 13 10:05:29 PDT 2012


On Apr 12, 2012, at 11:25 PM, Norbert Lindenberg wrote:

> What about functions that take two or more independent optional arguments, where sometimes you want to omit the first argument while providing the second?

arguably, this is where you should be using an options argument rather than multiple positional parameters with default values.  Certainly for the "or more" case.

> 
> For example, in the ECMAScript Internationalization API:
> 
>   Intl.Collator = function(localeList, options) { ... }
> 
> currently fills in default values for both localeList and options if they're undefined or not provided. The localeList parameter comes first because most applications will want to specify it, while the options are more optional. Some rare applications however may be OK with the browser's default locale and still need to specify options. In that case, the current spec of the Internationalization API lets them use
> 
> new Intl.Collator(undefined, {usage: "search"});

I'suggest that this is better written as:

     new Intl.Collator(Intl.LocalList(), {usage:"search"});

It would probably even better is Intl provided more explicit access to the default locale:

     new Intl.Collator(Intl.defaultLocale, {usage:"search"});

If it is indeed a rare usage then it is better to be explicit in the code rather than depending upon the code reader to ponder the intended meaning of a seldom used explicit undefined.


> 
> It seems the current proposal for optional arguments would not let us use
> 
>   Intl.Collator = function(localeList = defaultLocaleList, options = {}) { ... }
> 
> because undefined as the argument value would prevent the default value from being used, and there's no good way for the caller to say "please use the default value for this non-trailing argument".

You would still declare the formals as above.  But in addition, the body should contain a:
      localeList = localeList || defaultLocaleList;

or perhaps:

     localeList = localeList === undefined ? defaultLocaleList : localeList;

If you don't want other falsy arguments such as null to also trigger use of the default.

Allen





More information about the es-discuss mailing list