Top 5 Use Cases of Spread Operator in JavaScript

Top 5 Use Cases of Spread Operator in JavaScript

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 = [

// [ 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];
//['w', 'e', 'l', 'c', 'o', 'm', 'e']

5. Remove duplicate values from the array

const arr = [ 'apple', 'apple', 'banana', 'orange' ]
const uniqueArray = [ Set(arr) ]
// ['apple', 'banana', 'orange']

Subscribe to our Newsletter

Stay up to date! Get all the latest posts delivered straight to your inbox.

If You Appreciate What We Do Here On TutsCoder, You Should Consider:

If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.

Support Us

We are thankful for your never ending support.

Leave a Comment