Use Cases for the Spread Operator | Tiffany R. White Blog

Use Cases for the Spread Operator

Reading time: 1 min

One of the coolest features of ES6 is the Spread Operator. The syntax looks a bit like:

let a = [4, 5, 6];
let b = [7, …a, 8];


This will give us:

The spread operator replaces the concat function in ES5:

“use strict“;
var a = [4, 5, 6];
var b = [7].concat(a, [8]);


This is a great little feature, but what can we do with it?

Some Uses for the Spread Operator

We can do a lot with the spread operator.

Combine Arrays

You can use the spread operator to combine arrays:

let test = () => {
  let arr1 = ['foo', 'bar','baz'];
  let arr2 = ['fizz', 'buzz'];
  arr1.push(...arr2); // Will append the contents of arr2 to arr1

test(); // Runs function

Copying Arrays

We’ve used Array.prototype.slice to make copies of arrays. Now we can do that with the spread operator.

let arr = [7, 8, 9];
let arr2 = […arr];
arr2.push(10); // Will return a deep copy of the array with 10 appended to the end
//of the values

More At the MDN

You can find more uses for the spread operator at the MDN.

No Ads. No Sponsored Content. Ever.

I've decided that I no longer want to have sponsored posts on this blog. I also, though as tempting as it may sound, don't want ads; even if I got big enough for Carbon ads I don't want them. I want to post free, engaging content for beginning/junior devs. This means that I won't have Setapp posts or affiliates on this blog, though I will keep them on the Uses page. If you enjoy the content, buy me a coffee. Just click the button below.

Webmentions 0

No webmentions were found.