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.π
Top comments (0)