In ES6 , if there is any feature which can be marked as underrated , that has to be Spread Operator often represented by three dots.(…)
It’s importance could be found by such a way that it is impossible to move forward in React or Redux without knowing how spread syntax works.
Spread operator simply spreads or open up the datatype on which spread operator is applied and than can be used as per choice.
So,let’s see some of the most common usage of Spread syntax in JavaScript.
- Usage in Array
const arr = [1,2,3,4];
const endArr = [...arr,5];
Result : [1,2,3,4,5]
const startArr = [0,...arr];
Result : [0,1,2,3,4,5]
const bettweenArr = [0,...arr,5];
Result : [0,1,2,3,4,5]`
So, as evident in above example , when we initialize a new variable as an array , and spread an array within it.It opens up the spread ed datatype and merges with the rest of the element.
2.Usage in Object
const obj1 = { language : "Javascript", profile : "Web Developer" }
const obj2 = { language:"Java", profile:"Backend Developer" }
const obj3 = {...obj1,...obj2} Result : { language: 'Java', profile: 'Backend Developer' }
Here , above obj1 and obj2 are merged in a single Object by using spread operator.
Please note whenever we use spread operator to create a new Object a new instance is created.
Please note multiple objects can be merged into a single object using the above assignment and the common properties are overridden by the latest one(rightmost).
For eg -
const obj3 = {...obj1,...obj2,...{language : 'Python'}} Result : { language: 'Python', profile: 'Backend Developer' }
- A Common usage
One common usage of spread operator is when we have an input data in the form of array but a function expects the same in the form of string.
For eg => Suppose we want to find maximum among an array of integers .
const arr = [31,13,46,05]
One way to do is by using apply method on max method of Math Object.
console.log(Math.max.apply(null,arr))
Result => 46
However , the same can be implemented by using the spread operator:
console.log(Math.max(...arr))
Result => 46
So, this in nutshell is all about basic usage of ES6 Spread operator.Hope you learned something new today
Do like it , if it was of any help and do share and …ing