Tip 7: Mold Arrays with the Spread Operator
In this tip, you’ll learn how to simplify many array actions with the spread operator.
Spread operator
As you’ve seen, arrays provide an incredible amount of flexibility for working with data. But the number of methods that an array contains can be confusing, and it could lead you to some problems with mutations and side effects. Fortunately, the spread operator gives you a way to create and manipulate arrays quickly with minimal code.
The spread operator, symbolized with three dots (...
), may be the most widely
used new feature in JavaScript. You’re likely to find it in nearly every file
containing ES6+ syntax.
That said, it’s hard to take the spread operator seriously. I certainly didn’t. What it does is so mundane: It converts an array to a list of items. Turns out, that tiny action has many benefits that we’ll explore in the next few tips.
The benefits don’t end with just arrays. You’ll see the spread operator over
and over. It pops up in the Map
collection, as you’ll see in Tip 14, Iterate Over
Key-Value Data with Map and the Spread Operator. You’ll use a
variation called the rest operator in functions, as you’ll see in Tip 31, Pass a
Variable Number of Arguments with the Rest Operator. And you
can use the spread operator on any data structure or class property using generators,
as you’ll see in Tip 41, Create Iterable Properties with Generators.
Example: Using the spread operator on arrays
I hope that I’ve sparked your interest. To start, try using the spread operator on a simple array.
You begin with an array of items.
Get hands-on with 1400+ tech skills courses.