Utilities of spread operator in JavaScript

Syntax

const numArray = [1,2,3,4];
const profile = { name: ‘techsith’ , age: 30 };

Create a shallow copy of an array

const numArray = [1,2,3,4];
...numArray     // 1,2,3,4
const newArray = [...numArray]  // [1,2,3,4]
const profiles = [{
name: 'techsith',
age: 30
},
{
name: 'john',
age: 20
}];
const clonedProfiles = [...profiles];clonedProfiles[0].name = 'peter';console.log(profiles[0].name); //peter.

Merging arrays

const array1 = [1,2,3,4];
const array2 = [5,6,7];
(Visualize)...array1  //1,2,3,4...array2  //5,6,7
(Visualize)...array1, ...array2  // 1,2,3,4,5,6,7
const mergedArray = [...array1, ...array2]  // [1,2,3,4,5,6,7]

Merging Objects

const profile1 = {
name: 'techsith',
age: 30
};
const profile2 = {
name: 'techsith',
age: 40,
website: 'techsith.com'
};
(Visualize)...profile1 // name: 'techsith', age: 30...profile2 // name: 'techsith', age: 40, website: 'techsith.com'
(Visualize)...profile1, ...profile2 // name: 'techsith', age: 30 , name: 'techsith', age: 40, site: 'techsith.com'
(Visualize)...profile1, ...profile2// name: 'techsith', age: 40, site: 'techsith.com'
const newProfile = { ...profile1, ...profile2 }  /* 
{
name: 'techsith',
age: 40,
site: 'techsith.com'
}
*/

Rest parameters

let addTwo = (a, b) => a + b;let addThree = (a, b, c) => a + b + c;
let add = (...n) => n.reduce((total, i) => total + i);console.log(add(1,2,3)) // 6
console.log(add(1,2,3,4)) // 10

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store