Loading...
JavaScript

Spread Operator in JavaScript

The spread operator (...) is a new powerful feature introduced in JavaScript ES6. It allows expansion of iterables such as arrays, objects, and function’s arguments in place where zero or more elements (for array), zero or more key-value pairs (for object literals) and zero or more arguments (for function calls) are expected. In short the spread operator expands an iterable object into the list of arguments.

Example: Spreading array into arguments

function sum(x, y, z) {
  return x + y + z;
}
// Pass each element of array as argument
sum(...[1,2,3]) // Output: 6

function someFun(x, ...y) {
  // y is an Array
  return x * y.length;
}
someFun(2, "hello", "world") // Output: 4

Other Usage of Spread Operator

Combine or Merge Arrays and Objects:

let arr1 = [1, 2, 3];
let arr2 = [4, 5];
let combinedArr = [...arr1, ...arr2];
console.log(combinedArr) //Output: [1, 2, 3, 4, 5]

let obj1 = {"name": "Sam", "age": 25};
let obj2 = {"city": "Bengaluru"};
let combinedObj = {...obj1, ...obj2};
console.log(combinedObj) // {"name": "Sam", "age": 25, "city": "Bengaluru"}

Clone or Copy Arrays and Objects:

In JavaScript every non-primitive entity is an Object, which means that arrays are also objects. You should note that objects are copied as a reference and not as value. So, if you do any changes in copied object, the changes will reflect in the original object too.

let arr1 = [1, 2, 3];
let arr2 = arr1; // Copy
arr2.push(4);
console.log(arr1) //Output: [1, 2, 3, 4]
console.log(arr2) //Output: [1, 2, 3, 4] 

We can resolve this issue using spread operator as shown in the examples below:

let arr1 = [1, 2, 3];
let arr2 = [...arr1]; // Clone arr1
arr1.push(4);
console.log(arr1) //Output: [1, 2, 3, 4]
console.log(arr2) //Output: [1, 2, 3] 

let obj1 = {"name": "Sam", "age": 25};
let obj2 = {...obj1}; // Clone obj1
obj1.city = "Bengaluru";

console.log(obj1) //Output: {"name": "Sam", "age": 25, "city": "Bengaluru"}
console.log(obj2) //Output: {"name": "Sam", "age": 25};

Note that spread operator does shallow copy of object and not deep copy. This means nested object cannot be copied using ... operator.

Share this article with your friends
Leave a Reply

Your email address will not be published. Required fields are marked *