JavaScript’s Spread Operator

The spread operator is handy when you want to call a function with some arguments and you have those arguments in the form of an array. It lets you pass the array, and spreads the contents of the array across the arguments expected by your function.

It’s a situation like this:

function getTotal(a, b, c) {
    return a + b + c;
}

let params = [1, 2, 3];

I can’t call getTotal(params) here. getTotal wants individual parameters, not a single array.

I could do the spread manually, in code:

getTotal(params[0], params[1], params[2]);

Kind of unpleasant, verbose. And it doesn’t really work if I want to support situations where params can have a variable length.

I could use Function.prototype.apply for that:

getTotal.apply(null, params).

Reasonable, but still not ideal. Before ECMAScript 2015, this is what I’d have suggested you do.

The spread operator is a nicer, cleaner way:

getTotal(...params);

Looks like the syntax for rest parameters, right? I’m sure that’s no coincidence. They represent similar concepts, just in different directions. In a function definition, the dot-dot-dot says “turn this list of args into an array”. In an invocation, the dot-dot-dot says “turn this array into a list of args”.