In this, tutorial we will see some most useful use cases of spread operators in javascript.

Also read, Spread Operator in JavaScript

1. Use Spread for Merging Array

const array1 = [1, 2, 3];

const array2 = [4, 5, 6];

const mergedArray = [
  ...array1,
  ...array2
];

// [ 1, 2, 3, 4, 5, 6 ] ;

2. Clone Array (Shallow Copy)

const arr1= ['john', 'steev'];
const arr2 = [...arr1];

arr1; // ['john', 'steev']
arr2; // ['john', 'steev']

3. Convert Node List to Array

We normally using document.querySelectorAll to get a NodeList, and to use it with map,forEach or any other loop we need to convert it to Array, which we can do using the Spread operator like this:

const nodeList = document.querySelectorAll('img');

const array = [...nodeList];

4. Splitting the word

let string = "welcome";
let split = [...string];
console.log(split);
//['w', 'e', 'l', 'c', 'o', 'm', 'e']

5. Remove duplicate values from the array

const arr = [ 'apple', 'apple', 'banana', 'orange' ]
const uniqueArray = [ ...new Set(arr) ]
console.log(uniqueArray) 
// ['apple', 'banana', 'orange']