What's the Spread Operator Used For in JavaScript?
source link: https://www.digitalocean.com/community/tutorials/js-spread-operator
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
// Tutorial //
What's the Spread Operator Used For in JavaScript?
Learn about the ES6 spread operator, and some practical uses for this powerful JavaScript feature!
The spread operator is a feature of JavaScript introduced with ES6 that gives you access to the insides of an iterable object. The term “iterable object” is really just a computer science-y term for a category of data types. Specifically: arrays, objects literals, and strings.
What makes them “iterable”? These kinds of JavaScript types can be traversed in some sequential fashion. For example, you can use a for loop on an array, or with object literals you can use for…in loops.
The spread operator effectively gives you access to the “stuff” inside these iterable objects. Let’s look an example to illustrate what that means:
const foo = [
'hello',
'bonjour',
'konnichiwa'
];
const bar = [...foo]; // the three dots "..." are the spread operator syntax!
console.log(bar);
// ['hello', 'bonjour', 'konnichiwa'];
The variable bar
got an exact copy from foo
! Whoa…
const foo = [
<^>'hello',
'bonjour',
'konnichiwa'<^>
]
const bar = [...foo]
The spread operator essentially scooped out the insides of the foo
array and spread the values across the new array in bar
.
Now that we have a basic idea, let’s look at common tasks where the spread operator might be useful.
Duplicating Iterable Objects
As we saw earlier, the spread operator is one of the best ways for duplicating an iterable object. There are more complex ways to do this, but the conciseness of the spread operator makes it delightfully easy.
const foo = ['hello', 'bonjour', 'konnichiwa'];
const bar = ...foo; // uh-oh :<
Kinda pulled a sneaky on ya. You have to drop it into a new set of brackets in bar
! 😬
const foo = ['hello', 'bonjour', 'konnichiwa'];
const bar = [...foo]; // woohoo! :>
console.log(bar);
// ['hello', 'bonjour', 'konnichiwa']
Using the spread operator to duplicate object literals isn’t much different than arrays. Just remember to BYOB (bring your own brackets):
const foo = {
english: 'hello',
french: 'bonjour',
japanese: 'konnichiwa'
};
const bar = {...foo};
console.log(bar);
// { english: 'hello', french: 'bonjour', japanese: 'konnichiwa' }
Merging Iterable Objects
The spread operator can also be used to compose a single value from several other values!
const foo = ['hello', 'bonjour', 'konnichiwa'];
const bar = ['gutentag', 'hello-ey'];
const baz = [...foo, ...bar];
console.log(baz);
// ['hello', 'bonjour', 'konnichiwa', 'gutentag', 'hello-ey']
Now baz
is the merged value of both foo
and bar
. You can also place the spreaded array inside another array:
const foo = ['hello', 'bonjour', 'konnichiwa'];
const bar = [...foo, 'gutentag', 'hello-ey'];
console.log(bar);
// ['hello', 'bonjour', 'konnichiwa', 'gutentag', 'hello-ey']
This is where your well-trained JavaScript instincts might think this looks really weird… But remember that the spread operator just holds the “stuff”. Where you put that “stuff” is up to you! 💫
How about object literals? It’s very similar to merging arrays:
const foo = {
english: 'hello',
french: 'bonjour',
japanese: 'konnichiwa'
};
const bar = {
german: 'gutentag',
canadian: 'hello-ey'
};
const baz = {...foo, ...bar};
console.log(baz);
// { english: 'hello', french: 'bonjour', japanese: 'konnichiwa', german: 'gutentag', canadian: 'hello-ey' }
Boom! This used to be a task for Object.assign() but the spread syntax makes this far more concise.
What happens when there’s duplicate keys?
const foo = {
english: 'hello',
french: 'bonjour',
japanese: 'konnichiwa'
};
const bar = {
english: 'howdy',
german: 'gutentag'
};
const baz = {
...foo,
...bar,
canadian: 'hello-ey',
korean: 'annyeong'
};
console.log(baz);
// { english: 'howdy', french: 'bonjour', japanese: 'konnichiwa', german: 'gutentag', canadian: 'hello-ey', korean: 'annyeong' }
The duplicate keys are overwritten!
Remember that the ellipses go in front of the variable not after: ...myVariable
not myVariable...
Feeding Arguments into Functions
You may encounter this less often, but you can also use the spread operator for feeding arguments into a function.
const cube = [12, 30, 14];
function calcVolume(width, height, depth) {
return width * height * depth;
};
calcVolume(12, 30, 14); // basic
calcVolume.apply(null, cube); // using "apply"
calcVolume(...cube); // using "spread operator"
The spread operator makes it incredibly easy to feed a series of arguments into functions.
You Said Something About Strings
Lastly, you can also use the spread operator with strings since they’re also considered an iterable object (it has slice
, and length
functions!)
const foo = "jumanji";
const bar = [...foo];
console.log(bar);
// [ "j", "u", "m", "a", "n", "j", "i" ]
You may not encounter a need to use the spread operator for strings unless you develop software for natural language processing, or some kinda machine learning. I’m not sure… But it definitely works on strings!
Conclusion
The spread operator was a highly requested feature that was already available in old-school languages like C++ and Python, and now it’s here! It makes some common programming tasks really easy to do, and hopefully you learned practical ways you could use it!
See MDN for in-depth documentation on the spread operator.
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK