The spread operator, written with three consecutive dots (...), is new in ES6 and gives you the ability to expand, or spread iterable objects into multiple elements.
Let's take a look at a few examples to see how it works:
const books = ["Don Quixote", "The Hobbit", "Alice in Wonderland", "Tale of Two Cities"];
console.log(...books);
Prints: Don Quixote The Hobbit Alice in Wonderland Tale of Two Cities
If you look at the output from the examples, notice that both the array and set have been expanded into their individual elements. So how is this useful?
NOTE: Sets are a new built-in object in ES6.
Combining arrays with concat
One example of when the spread operator can be useful is when combining arrays
If you've ever needed to combine multiple arrays, prior to the spread operator, you were forced to use the Array's concat() method
The spread operator, written with three consecutive dots (
...
), is new in ES6 and gives you the ability to expand, or spread iterable objects into multiple elements.Let's take a look at a few examples to see how it works:
If you look at the output from the examples, notice that both the array and set have been expanded into their individual elements. So how is this useful?
Combining arrays with
concat
One example of when the spread operator can be useful is when combining arrays
If you've ever needed to combine multiple arrays, prior to the spread operator, you were forced to use the Array's
concat()
methodThis isn't terrible, but wouldn't it be nice if there was a shorthand way to write this code?