Hi, in this blog we will see spread operator bit by bit and understand it . so lets start π₯
πIn JavaScript spread operator is used very frequently specially when we want to clone an array or an object . lets see it through an example.
let arr1=["mango" , "orange", "apple"];
let arr2=[...arr1];
output:- arr2= ["mango" , "orange", "apple"]
In the above example , In order to make a clone of arr1 , you can use spread operator to spread the elements of arr1 in an empty array[ ] .
yeah! you're right spread operator is that simple!
πNow lets see it in case of an object , when we want to clone an object .
const obj1= { name:"anjali", age:5 }
const obj2= { ...obj1 }
output:- obj2 = { name:"anjali", age:5 }
Here , spread operator will spread all the key-value pair of obj1 .
πNow , I know you folks were thinking π€ that if we want to add some other elements also in arr2 with the elements of arr1 , then how we will do it .
so, the answer is - Lets see with an example -
let arr1=["mango" , "orange", "apple"];
let arr2=[...arr1,"grapes","pineapple"];
output:-arr2= ["mango" , "orange", "apple","grapes","pineapple"]
const obj1= { name:"anjali", age:5 }
const obj2= { ...obj1, hobby:"singing", country:"india" }
output:- obj2 = {name:"anjali", age:5, hobby:"singing", country:"india"}
Alright, so folks in the above example you can see that spread operator will spread the elements of arr1 in case of arrays and in case of objects you can see , spreads obj1 elements , and in addition if we want to add more elements , then we can also write that elements .
πYou can also spread multiple arrays or objects in an array or object . so lets see with an example-
let arr1=["mango" , "orange", "apple"];
let arr2=["grapes","pineapple"];
let arr3=[...arr1,...arr2];
output:- arr3 = ["mango" , "orange", "apple","grapes","pineapple"]
const obj1= { name:"anjali", age:5 }
const obj2 = { hobby:"singing", country:"india"}
const obj3= { ...obj1, ...obj2 }
output:- obj3 = {name:"anjali", age:5, hobby:"singing", country:"india"}
so, lets end this topic here it is more than enough about spread operators .
πIf you want to understand other cloning methods or why we need to do cloning or other concepts of JavaScript like primitive and non primitive (reference types) , hoisting, callback functions , difference between let, var, const or high order functions or any thing , that you want to understand then let me know in the comment . if you have any questions then write it in comment section . subscribe this newsletter only if you find it helpful .
If you like my work, you can buy me a coffee and share your thoughts buymeacoffee.com/yashika227x .