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