Code Premix

JavaScript Spread Operator

📅June 24, 2021|🗁JavaScript

Today we will explain you about the JavaScript Spread Operator.

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.

  1. Immutable copy an array or object
  2. Concatenating arrays or objects
  3. Spreading elements together with an individual element
  4. 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.

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.

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.

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.

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.

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

That’s it for today.
Thank you for reading. Happy Coding..!!