Background

Requirements/Goals

  • Replace an array or array-like actual parameter value with its elements as positional parameters
  • Let new compose with a this-free form of apply
  • Remove (some day, and in similar future methods) automagic (and half-the-time wrong) array flattening, e.g. in Array.prototype.concat

Sketch

  • Let ... be a unary prefix operator called spread, with the same precedence as delete, typeof, !, etc.
  • The ... operator is legal only within an actual parameter list
  • Evaluate ... arg in a parameter list by evaluating arg and then replacing it with arg[0] through arg[arg.length - 1].
// Expand an array as element-wise positional parameters
function q(x, a, b, c) {
    return a * x * x + b * x + c;
}
var a = read_triple();
var x = read_value();
print(q(x, ...a));

// Compose new with this-free apply:
var date_fields = read_date_fields(database);
var d = new Date(...date_fields);

Issues

  • There’s no obvious reason why ... should not work on any object with a length property and elements limited by length as ES5 Function.prototype.apply does.
    • So if arg evaluates to an object without length, spread throws an exception.
  • In the same vein, I don’t see why ... should not be allowed before any actual parameters, not required (if present) to be before only the last parameter. If a future edition of the language enforces arity checking, it will have to do so at runtime, or else have sufficient compile-time analysis to decide arg.length and report an early error if it can.

Brendan Eich 2009/05/04 22:09

We also discussed allowing the spread operator in array literals as a way to expand arrays

let a = [2, 3];
let b = [1, ...a]; // [1, 2, 3]
let c = [0, ...b, 4]; // [0, 1, 2, 3, 4]

Erik Arvidsson 2009/07/30 19:07

 
harmony/spread.txt · Last modified: 2009/07/30 22:19 by brendan
 
Recent changes RSS feed Creative Commons License Donate Powered by PHP Valid XHTML 1.0 Valid CSS Driven by DokuWiki