Spread Operator

One new syntax added to JavaScript as a part of ES20115 is what is known as the spread operator. This operator has various uses such as being able to pass an iterator or array to a function and have the iterations and array entries expanded into individual parameters.

For example: disp(...x); where x is an iterator will pass all of the iterations as separate parameters to the disp() function. So if x is the array ['a','b','c'] then disp will receive those values as three separate parameters (just as if you had called disp.apply(disp,x). Of course not all uses of the spread operator are so simple. You could have other parameters being passed to the function as well as the spread operator and even multiple instances of the spread operator eg. disp(a, ...b, c, ...d, e) which needs to expand each spread operator.

There is no way we can create a polyfill for the spread operator as older versions of JavaScript simply don't recognise the syntax. So we can't just use the spread operator as shown in the following code and expect it to work:

var a = 1;
var b = [2,3];
var c = [4,5,6].values();
disp(a, ...b, ...c);

That code is equivalent to disp(1,2,3,4,5,6) but older versions of JavaScript don't understand the spread operator and so cannot expand out the array in ...b or the iterator in ...c and so we can't use this new construct until all the browsers that don't support it have died out. There is a relatively straightforward solution though. While we can't get old versions of JavaScript to accept that code as it is we can get JavaScript to recognise a minor variant of that code and have it do the same thing. Instead of marking each value to be spread individually with ... we can tell the function that one or more of the parameters needs the spread operator to be applied by adding .__ to the end of the function name.

disp.__(a, b, c)

Now the function will not care about which of the parameters being passed needs the spread operator applied.

Now this .__ isn't part of JavaScript either - at least not without a little more work. Now __ is a valid but unusual function/method name and so we can define a new method on the Function object that has this name. This method simply needs to examine each argument. If it is an ordinary variable then pass it straight through but if it is an array or iterator then pass the individual values as separate parameters.

All we need to do to implement our own variant on the spread operator that works like this is the following method definition.

Function.prototype.__ = function() {
var argsin, argsout, i, r;
argsout = [];
argsin = [].slice.call(arguments);
for (i = 0, ii = argsin.length; i < ii; i++) {
if (Array.isArray(argsin[i])) {
argsout = argsout.concat(argsin[i]);
} else if (argsin[i].next) {
for (r = argsin[i].next(); !r.done; r = argsin[i].next()) {
} else {
return this.apply(this, argsout);


This article written by Stephen Chapman, Felgall Pty Ltd.

go to top

FaceBook Follow
Twitter Follow