Spread Operator in JavaScript
Today we will explain you about the spread operator in JavaScript. Spread Operator is introduced by JavaScript ES6 (ECMAScript 6). The syntax is three dots(…) followed by the array (or iterable*). Spread operator allows iterables(arrays/objects/strings) to be expanded into single arguments/elements.
Spread Operator in JavaScript, Understanding the Spread Operator in JavaScript, Difference between Rest and Spread Operator in JavaScript ES6 (ECMAScript 6). How to use three or triple dots(…) in JavaScript.
Checkout more articles on JavaScript
Use of Spread Operator
- Immutable copy an array or object
- Concatenating arrays or objects
- Spreading elements together with an individual element
- Spreading elements in function arguments
1. Immutable copy an array or object
With the use of spread operator we can create the immutable object or array which will not affect on another variable.
1 2 3 4 5 6 | let arr1 = ['A','B','C']; let arr2 = [...arr1]; console.log(arr2); // Output: ['A','B','C'] arr2.push('D'); console.log(arr2); // Output: ['A','B','C', 'D'] console.log(arr1); // Output: ['A','B','C'] |
Same things you can manage it for object as well.
2. Concatenating arrays or objects
If you want to concat the two arrays or objects then you can use the spread operator.
1 2 3 4 | let arr1 = ['A', 'B', 'C']; let arr2 = ['X', 'Y', 'Z']; let result = [...arr1, ...arr2]; console.log(result); // Output: ['A', 'B', 'C', 'X', 'Y', 'Z'] |
Let’s take an example for an object. If your object attribute is same then it will be update the new value in attribute.
1 2 3 4 | let obj1 = {A:1, B:2, C:3}; let obj2 = {A:7, Y:8, Z:9}; let result = {...obj1, ...obj2}; console.log(result); // Output: {A:7, B:2, C:3, Y:8, Z:9} |
In the above example A
attribute is exist in both objects. So when you merge it then it will update the new value as 7
in A
attribute.
3. Spreading elements together with an individual element
Here we are spreading elements together with an individual element and get the updated array.
1 2 3 | let arr1 = ['A','B','C']; let arr2 = ['A0', ...arr1]; console.log(arr2); // Output: ['A0', 'A','B','C'] |
4. Spreading elements in function arguments
We can also spread the elements in function arguments by the use of spread operator.
1 2 3 4 5 6 7 8 9 | let arr1 = ['1','2','3']; var sum = (f1, f2, f3) => { console.log(`Elements - ${f1}, ${f2} and ${f3}`); // Output: Elements - 1, 2 and 3 return f1 + f2 + f3; // Output: 6 } sum(...arr1); // Output: // Elements - 1, 2 and 3 // 6 |
Thanks for reading. Happy Coding!