SPREAD OPERATOR
The JavaScript spread operator ( ... ) allows us to quickly copy all or part of an existing
array or object into another array or object.
Array Expansion
You can use the spread operator to expand elements of an array into another array:
const numbers = [1, 2, 3];
const moreNumbers = [4, 5, ...numbers];
console.log(moreNumbers); // [4, 5, 1, 2, 3]
Array Copying
You can create a shallow copy of an array:
const original = [1, 2, 3];
const copy = [...original];
console.log(copy); // [1, 2, 3]
Merging Arrays
You can merge multiple arrays easily:
const array1 = [1, 2];
const array2 = [3, 4];
const merged = [...array1, ...array2];
console.log(merged); // [1, 2, 3, 4]
Object Expansion
You can use the spread operator to copy and merge objects:
const obj1 = { a: 1, b: 2 };
const obj2 = { b: 3, c: 4 }; // Merging objects
const mergedObj = { ...obj1, ...obj2 };
console.log(mergedObj); // { a: 1, b: 3, c: 4 }
Object Copying
You can create a shallow copy of an object:
const originalObj = { a: 1, b: 2 };
const copyObj = { ...originalObj };
console.log(copyObj); // { a: 1, b: 2 }
Adding Properties
You can also use it to add properties while copying:
const obj = { a: 1, b: 2 };
const newObj = { ...obj, c: 3 };
console.log(newObj); // { a: 1, b: 2, c: 3 }