Surendar Vinayagamoorthy

Surendar Vinayagamoorthy

Spread ... The Love In JavaScript ❣️

Subscribe to my newsletter and never miss my upcoming articles

As per the MDN, below is the definition of the Spread Operator in JavaScript.

Spread syntax allows an iterable such as an array expression or string to be expanded in places where zero or more arguments (for function calls) or elements (for array literals) are expected, or an object expression to be expanded in places where zero or more key-value pairs (for object literals) are expected.

As a fan of clean code, I always fancied the use of Spread (...) operator. Below are some the useful implementations of the Spread operator.

Deep Copy Array

// Deep Copy Array
const sourceArray = [1, 2, 3, 4];
const copiedArray = sourceArray;
const copiedArrayUsingSpread = [...sourceArray];

sourceArray.pop();

console.log(copiedArray); // [ 1, 2, 3 ]
console.log(copiedArrayUsingSpread); // [ 1, 2, 3, 4 ]

Deep Copy Object - Single Level

As per Naina comments in discussion, deep copy works only with single level object. The spread operator will not be able to deeply copy the nested object.

// Deep Copy Object
const person = { name: 'John' };
const copiedPerson = person;
const copiedPersonUsingSpread = { ...person };
person.name = 'Doe';

console.log(copiedPerson); // { name: 'Doe' }
console.log(copiedPersonUsingSpread); // { name: 'John' }

Array Concatenation

// Array concatenation
const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];
const joinedArray = [...arr1, ...arr2];
console.log(joinedArray); // [ 1, 2, 3, 4, 5, 6 ]

Object Property Concatenation

// Object concatenation
const obj1 = { prop1: 'value1' };
const obj2 = { prop2: 'value2' };

console.log({ ...obj1, ...obj2 }); // { prop1: 'value1', prop2: 'value2' }

As Function Params

Functions in javascript can have required and optional params. Sometimes the there can be n optional params and this is where the ... operator comes in. Sometimes it may be referred to as Rest operator.

const numbers = [1, 5, 7, 2, 3, 4, 5, 7, 90];
console.log(Math.max(...numbers)); // 90

const multiplyBy = (multiplier, ...numbers) => {
  console.log(numbers.map((num) => num * multiplier));
};

multiplyBy(2, 1, 2, 3, 4, 5, 6); // [ 2, 4, 6, 8, 10, 12 ]

Hope the above snippets explain themselves. Let me know on how I could improve the contents in the comment section or tweet @radnerus93. To stay more connect you could follow me on twitter @radnerus93.

 
Share this