ES6 Everyday: Spread Operator

This one can be a little confusing at first: ES6 provides a new spread operator (...) that allows you to expand an expression into multiple elements.

Got it? Me neither.

Let’s look at an example.

What if we had an array of fruits we want to buy and we want to insert them within an existing groceryList array:

var fruitList = ['apple', 'strawberries', 'oranges'];

var groceryList = ['trash bags', fruitList, 'yogurt'];

// We end up with an array within an array:
// ['trash bags', ['apple', 'strawberries', 'oranges'], 'yogurt']

console.log(groceryList[1]);
// apple,strawberries,oranges

In the example above, the array is just sitting within the other array. But with the spread operator:

var fruitList = ['apple', 'strawberries', 'oranges'];

var groceryList = ['trash bags', ...fruitList, 'yogurt'];

// Now we have just one array:
// ['trash bags', 'apple', 'strawberries', 'oranges', 'yogurt']

console.log(groceryList[1]);
// apple

console.log(groceryList[2]);
// strawberries

The array has been expanded into just another list of elements. Cool, right?

(Check it out for yourself in a ES6 Fiddle.)

Resources