author avatar

sachin.kabadi

Thu Apr 11 2024



Spread operator in JavaScript is represented by three dots (...). 
It's a useful syntax for manipulating arrays and objects in various ways.

Following are some of the use cases:-

Spread in Arrays:-

1. Copying Arrays: It allows you to create a new array by copying another array.

const originalArray = [1, 2, 3];
const copyArray = [...originalArray];
console.log(copyArray); // [1, 2, 3]


2. Concatenating Arrays: You can merge arrays together.

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

3. Adding Elements to Arrays: You can add new elements to an existing array.

const array1 = [1, 2, 3];
const newArray = [...array1, 4, 5, 6];
console.log(newArray); // [1, 2, 3, 4, 5, 6]



Spread in Objects:-

1. Copying Objects: It allows you to create a shallow copy of an object.

const originalObj = { name: 'John', age: 30 };
const copyObj = { ...originalObj };
console.log(copyObj); // { name: 'John', age: 30 }

2. Merging Objects: You can merge multiple objects into one.

const obj1 = { name: 'John' };
const obj2 = { age: 30 };
const mergedObj = { ...obj1, ...obj2 };
console.log(mergedObj); // { name: 'John', age: 30 }

3. Adding Properties to Objects: You can add new properties to an object.

const obj1 = { name: 'John' };
const newObj = { ...obj1, age: 30 };
console.log(newObj); // { name: 'John', age: 30 }



Function Arguments:

1. Spread can be used to pass an array as individual arguments to a function.

const numbers = [1, 2, 3];
const sum = (a, b, c) => a + b + c;
console.log(sum(...numbers)); // 6