🔗What is spread Operator ?
ES6 provides a new operator called spread operator that consists of three dots (...)
The spread operator “spreads” the values in an iterable (arrays, strings) across zero or more arguments or elements.
🔗Array example
let's assume we have 2 array and we want to combine these 2 arrays how would we do ?
we can archive that by using concat method
jsconst arr1 = [1, 2, 3];const arr2 = [4, 5, 6];const combineArra = arr1.concat(arr2);console.log(combineArra); // [1, 2, 3, 4, 5, 6]
It would be nicer to be able to do something like this: [1, 2, 3, 4, arr2]
we can also archive that with spread Operator
jsconst arr4 = [4, 5, 6];const arr3 = [1, 2, 3, ...arr4];console.log(arr3); // [1, 2, 3, 4, 5, 6]
🔗Object example
Spread is also great for shaping a new object from other object(s):
jsconst defaults = {avatar: "avtar.jpg",active: true,};const userData = {username: "codingsumit",name: "sumit harijan",};const result = {created: "2021-15-10",...defaults,...userData,};console.log(result);
🔗What is rest parameters (…)
which is the same syntax as the spread operator, we can pass an unlimited number of parameters to our function .These parameters are available within our function as an array called args
jsconst randomFun = (...args) => {console.log(args); // [1, 2, 3, 4, 5]};randomFun(1, 2, 3, 4, 5);