ES6 - Spread Operator - Array

ES6 JavaScript

In this tutorial we will learn about the spread operator. So, let's get started.

The spread operator ... helps us to expand or unpack iterables like array, string, objects.

Spreading array

Let's say we have two arrays arr1 and arr2 like the following.

arr1 = [1, 2, 3]
arr2 = [4, 5, 6]

Now say, we want to merge arr1 and arr2 and get something like the following [1, 2, 3, 4, 5, 6].

We can think of different ways to find the solution. We can use loop and pick elements from each array and push them in a new array something like the following.

const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];
let result = [];

for (let i = 0; i < arr1.length; i++) {
  result.push(arr1[i]);
}

for (let i = 0; i < arr2.length; i++) {
  result.push(arr2[i]);
}

console.log(result); // [ 1, 2, 3, 4, 5, 6 ]

Using spread operator we can achieve the same result in a much simpler way like the following.

const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];

let result = [...arr1, ...arr2];
console.log(result); // [ 1, 2, 3, 4, 5, 6 ]

So, ...arr1 spreads or unpacks the elements inside array arr1 and ...arr2 spreads the elements inside array arr2.

Copy one array into another using spread operator

We can use the spread operator to copy elements of one array into other. In the following example we are copying the content of array arr1.

const arr = [1, 2, 3];
const copyArr = [...arr];