3 Dev hacks of JS ...spread Operator for Arrays
Himanshu_Sharma
Posted on August 20, 2022
Being a software Engineer, it's always learning new things, and implementing them on a loop๐. This post is about the JavaScript ES6 ...spread operator, to make your life easier, and code like a pro.๐
What is Spread Operator?
In simple words, it's just 3 dots(...) which can be applied to iterable, such as Arrays, Sets to combine/copy the elements. When applied to objects, it helps in updating/adding key-value pairs.
Let's understand how it's applied to arrays by a story.
Scene 1: You are working on a feature and you got 2 arrays with different elements to combine, how will you do it.
cosnt array1 = ["JS", "REACT", "GIT"]
const array2 = ["Node", "Mongo"]
Is this the approach you are following?
const newArray = array1.concat(array2);
console.log(newArray)
// output -> ["JS", "REACT", "GIT", "Node", "Mongo"]
If yes, then start using the below one, it's recommended, understandable, and more transparent.
const mergedArray = [...array1, ...array2];
console.log(mergedArray)
// output -> ["JS", "REACT", "GIT", "Node", "Mongo"]
Just for sake of understanding consider spread as "remove bracket and get all the elements inside them"๐
Scene 2: Let's say you have mergedArray, and now you want to clone it and perform some operations.
// we now have mergedArray= ["JS", "REACT", "GIT", "Node", "Mongo"]
Let's clone the array, it's super easy. Just an assignment.
const cloneArray = mergedArray;
clonedArray[0] = "Python";
conosle.log(clonedArray)
// ["Python", "REACT", "GIT", "Node", "Mongo"]๐
console.log(mergedArray)
// ["Python", "REACT", "GIT", "Node", "Mongo"]๐ฒ
Woo! you did not expect that to happen. Remember, an array is a reference type, when assigned to a variable, it will store the reference, not the actual value. So when you cloned merged array via "=" assignment operator, it stored the address, not the value. So the change made in cloned array, mutated actual array.
Then how to do it, don't worry spread operator to the rescue.โจ
const clonedArray = [...mergedArray];
clonedArray[0] = "Python";
conosle.log(clonedArray)
// ["Python", "REACT", "GIT", "Node", "Mongo"]๐
console.log(mergedArray)
// ["JS", "REACT", "GIT", "Node", "Mongo"]๐
Here spread operator is not referring to the address of mergedArray, instead it's copying the array at a new address, so that changes made on clonedArray does not mutate mergedArray.
Scene 3: Let's say you have an number array, how to get the max and min element from the array. Believe in ...spread๐
const numberArray = [22, 58, 46, 20, 5]
console.log(Math.max(...numberArray)) // -> 58
console.log(Math.min(...numberArray)) // -> 5
Thank you for spending valuable time reading this post, I am sure you learned something today.๐
Posted on August 20, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.