Spread and rest operators are two of the most useful pieces of shorthand in JavaScript. Spread operators allow us to expand an array or object into its individual elements, while rest operators allow us to condense multiple elements into a single array or object.
Spread operators are written using three consecutive dots (...), and they provide us with an easy way to break up an array or an object into its individual elements.
For example, let’s say we have the following array:
let array = [1, 2, 3, 4];
If we wanted to add a fifth element to our array, we could use the Spread Operator like this:
let newArray = [...array, 5];
The Spread Operator will take our array, expand it into its individual elements (1, 2, 3, 4), and then add the fifth element (5). The result is a new array that is one element longer than the original:
newArray = [1, 2, 3, 4, 5];
The rest operator is essentially the opposite of the spread operator. It collects multiple elements into an array. This is useful if you don’t know how many arguments a function may receive, and you want to capture all of them as an array.
The spread and rest operators are useful for quickly and easily manipulating collections and arguments. They make code much cleaner and easier to read, as well as reduce the number of lines of code needed.
They’re extremely versatile tools, and every JavaScript programmer should know how to use them.