Features Of ES6 Part 5: The Spread

Tuesday, September 2, 2014

The spread operator shares the same syntax we saw with rest parameters, a series of three dots (...). However, a rest parameter will collect individual parameters into an array when you use the dots in a function parameter definition, while the spread operator expands an array into individual parameters when using the dots in a function call.

let doWork = function(x, y, z) {
    return x + y + z;
}

var result = doWork(...[1, 2, 3]);
expect(result).toBe(6);

In the above code, the spread operator will “spread” the array of three values across the parameters x, y, and z.

The spread operator can also expand an array to create individual elements in an array literal.

var a = [4, 5, 6]; 
var b = [1, 2, 3, ...a, 7, 8, 9]; 

expect(b).toEqual([1,2,3,4,5,6,7,8,9]);

Although the examples here are all using the spread operator with an array, the spread operator also works with any iterable object. We’ll look at iterable objects in a future post.

The Impact of the Spread

Before rest parameters and the spread operator came along, Function.apply and the implicit arguments variable were widely used to accept an unknown number of arguments to a function and pass the arguments along to another function, like in the example below.

var doWork = function(x, y, z){
    return x + y + z;
}

var doSomething = function(){
    return doWork.apply(null, arguments);
}

var result = doSomething(...[1,2,3,4,5]);
expect(result).toBe(6);

The implementation of doSomething is cleaner and more obvious when using a rest parameter and the spread.

var doWork = function(x, y, z){
    return x + y + z;
}

var doSomething = function(...args){
    return doWork(...args);
}

var result = doSomething(...[1,2,3,4,5]);
expect(result).toBe(6);

Notice that when using the spread (or apply), you can have more values in the array than the destination function requires. The spread will start from the beginning of the array to populate parameters, so in the above example, doWork will see the first three values in the array.

Want more? Watch JavaScript Fundamentals for ES6 on Pluralsight!


Comments
Wednesday, September 3, 2014
Hi scott, I would like to know your opinion about the "implicitness" of the spread. To me (as a more c# than js developer ), it looks a little risky to call a function without equality between the number of arguments and the number of parameters (unlike with default parameters where it is due to explicit definition in the function itself)
gravatar Scott Wednesday, September 3, 2014
I think it can be useful in some limited scenarios, like when writing a wrapper function to add logging, something like the "doSomething" function above, typically the result of "monkey patching" a JavaScript object.
Comments are now closed.
by K. Scott Allen K.Scott Allen
My Pluralsight Courses
The Podcast!