Spread and non objects

Jason Orendorff jason.orendorff at gmail.com
Fri Nov 5 17:32:30 PDT 2010

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 || [])

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++)

or else

  var errors = [];  // an array to begin with
  // lots of code

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 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

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.


More information about the es-discuss mailing list