techStackGuru

JavaScript Spread Operator


Spread syntax is used to combine two existing arrays into one new array or object.

Syntax

array = [...array1,...array2]

Example

let array1 = [1,2,3];
let array2 = [4,5,6];

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

Example

let array1 = [1,2];
let array2 = [array1,3,4];
      
console.log(array2); // [ [ 1, 2 ], 3, 4 ]

Example

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

Example with objects

const array = [1, 2, 3, 4, 5];
const object = { ...array };
console.log(object); // { '0': 1, '1': 2, '2': 3, '3': 4, '4': 5 }

Example with objects

As we can see in example, response has been replaced by new value.

const object1 = { name: "John", age: 23 , city: "Mumbai" };
const object2 = { name: "Eric", age: 21 , Country: "India"};

const finalObject = { ...object1, ...object2 };
console.log(finalObject); // { name: 'Eric', age: 21, city: 'Mumbai', Country: 'India' }

Example

Lets get min and max using Spread operator.

const array = [1,3,9,-1,5,-7,];
  
console.log(Math.max(...array)); // 9
console.log(Math.min(...array)); // -7

Example with characters

const char = ['A', 'B', ...'CD', 'E'];
console.log(char); // [ 'A', 'B', 'C', 'D', 'E' ]