What is this … JavaScript operator

The … operator is called a spread operator. It’s an ES6 way of taking an array, or a string, and act as if it’s in a for loop.

That is to say, turn this.

// Old way
function sum(x, y, z) {
  return x + y + z;
}
let total = 0;
let some_numbers = [1,2,3];
total = sum(some_numbers[0],some_numbers[1],some_numbers[2]);    
console.log(total); // Expect this to print 21
// new way
let some_numbers = [1,2,3];
function sum(x, y, z) {
  return x + y + z;
}
let total = sum(...some_numbers);
console.log(total); // Expect this to print 21 too

As you can see in the code above. The array was split apart, so that the function, sum(a,b,c), which has three parameters, is getting each of those filled automatically by the array.

There’s an excellent write up about this function on the MDN web docks, https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax

I learned how to program before ES6 syntax was popular, so this has been an annoying little bit of extra syntax to learn. I hope this post reaches out to others who are in the same boat at I was.

Here’s a nice trick taken from the developer blog.

// used to get a copy of an array
let arr = [1, 2, 3];
let arr2 = [...arr];

Something to keep in mind, it doesn’t work on objects. It won’t get the keys, unfortunately, but it does work on Strings.