Spread and non objects

Brendan Eich brendan at mozilla.com
Fri Nov 5 17:46:28 PDT 2010


On Nov 5, 2010, at 5:32 PM, Jason Orendorff wrote:

> On Thu, Nov 4, 2010 at 8:07 PM, John Lenz <concavelenz at gmail.com> wrote:
>> It would seem friendlier for the spread operator to treat it them as a empty
>> array otherwise you end up with code like:
>> if (x!=null) {
>>   f(1,2,...x)
>> } else  {
>>   f(1,2)
>> }
> 
> I'm late to the party, but note that you could instead write
> 
>  f(1, 2, ...x || [])

You mean

  f(1, 2, ...(x || []))

at least.


> which doesn't seem like such a burden. And this seems like a rare case
> to me; the common case will be like
> 
>  function dispatch(...args) {
>      for (var i = 0; i < this.handlers.length; i++)
>          obj.handle(...args);
>  }
> 
> or else
> 
>  var errors = [];  // an array to begin with
>  // lots of code
>  report.push(...errors);
> 
> In cases like these, a null or undefined spread-argument would be a
> mistake. And when that happens, the programmer wants the problem to be
> detected as soon as possible, which means throwing an exception. The
> tradeoff here is between having to remember to add "|| []" when it's
> needed,

and parentheses.


> and the possibility that accepting undefined here would make
> simple typos pass silently:
> 
>  // Suppose we want to expand request.arguments into the arguments here.
>  log.write(msgid, ...request.args)   // oops, typo, should be request.arguments
> 
>  // Here the code around the ... is correct, but a caller makes a
>  // mistake that passes silently.
>  function dispatch(obj, method, args) { obj[method](...args); }
>  var myargs = [x, y, z];
>  dispatch(myobj, mymethod); // oops, forgot 3rd argument, but no error

Is the caller making a mistake or counting on something expected by comparison to Function.prototype.apply, or just by analogy to missing parameters not being errors?

This is mostly a rhetorical question, don't worry about answering. My point is more that users will expect what they expect, not what we think they ought to.


> Of course these things already pass silently, for programmers using
> Function.prototype.apply, thanks to a special case in the spec. But
> maybe we shouldn't have more of those. Every special case should have
> to justify its existence. Function.prototype.apply is a special case;
> most places that want an array-like object will throw if you pass null
> or undefined.

There's the special case of deviating from the Function.prototype.apply special case. Ok, I get it -- two wrongs don't make a right. Still, this is a close call.

/be



More information about the es-discuss mailing list