8 Ways to Use Spread Operator in Javascript
ELIMINATE DUPLICATES FROM AN ARRAY
To remove duplicates from an array
const num = [1, 2, 1, 4, 4, 1];
const uniqueNum = [...new Set(num)];
uniqueNum; //[ 1, 2, 4]
CONVERT STRING TO CHARACTER ARRAY
The string is also an iterable object, so we can use "..." to strings also.
let str = "Tech with Fahad";
let chars = [...str];
//["T", "e", "c", "h", " ", "w", "i", "t", "h", " ", "F", "a", "h", "a", "d"];
DESTRUCTURING VARIABLE
let [apple, ...fruits] = ["Apple", "Mango", "Orange", "Cheri"];
apple; // Apple
fruits; // [ 'Mango', 'Orange', 'Cheri' ]
CONVERT NODELIST OBJECT TO ARRAY
NodeLists are array-like but don't have all methods of Array, like forEach, map, filter, etc.
const nodeList = document.querySelectorAll(".class");
const nodeArray = [...nodeList];
PASSING AS AN ARGUMENT
function sum(a, b) {
return a + b;
}
let num = [10, 2];
sum(...num); // 12
MERGING ARRAYS
const fruits = ["Apple", "Orange", "Mango", "Cheri"];
const colors = ["Red", "Yellow", "Green"];
const result = [...fruits, ...colors];
//["Apple", "Orange", "Mango", "Cheri", "Red", "Yellow", "Green"];
COPYING ARRAYS
The spread operator does not perform DEEP-COPY.
const fruits = ["Apple", "Orange", "Mango", "Cheri",];
const copy = [...fruits];
console.log(...fruits); // Apple Orange Mango Cheri
IN LOGGING
We can use the spread operator in console.log with iterable objects.
const fruits = ["Apple", "Orange", "Mango", "Cheri"];
console.log(...fruits); // Apple Orange Mango Cheri
Comments
Post a Comment