Javascript spread operator
Created By: chatGPT
The spread operator in JavaScript, represented by three dots
(...)
, allows you to expand iterable objects into their individual elements. This operator is extremely useful for various operations, such as merging arrays or making copies.const array1 = [1, 2, 3];
const array2 = [4, 5, 6];
// Merging two arrays using spread operator
const mergedArray = [...array1, ...array2];
console.log(mergedArray); // Output: [1, 2, 3, 4, 5, 6]
Spreading objects also works similarly, allowing you to create a new object with the properties of the existing object. This is beneficial for copying and merging objects smoothly.
const obj1 = { a: 1, b: 2 };
const obj2 = { c: 3, d: 4 };
// Merging two objects using spread operator
const mergedObj = { ...obj1, ...obj2 };
console.log(mergedObj); // Output: { a: 1, b: 2, c: 3, d: 4 }
If you want to create a copy of an array or an object without referencing the original, the spread operator provides a simple solution.
const originalArray = [1, 2, 3];
const copiedArray = [...originalArray];
console.log(copiedArray); // Output: [1, 2, 3]
console.log(originalArray === copiedArray); // Output: false (different references)
const originalObject = { x: 10, y: 20 };
const copiedObject = { ...originalObject };
console.log(copiedObject); // Output: { x: 10, y: 20 }
console.log(originalObject === copiedObject); // Output: false (different references)
Another interesting use case for the spread operator is to pass array elements as function arguments. Rather than using
apply
, the spread operator makes it more readable.const numbers = [1, 2, 3];
// Using spread operator to pass elements as arguments
const sum = (...args) => args.reduce((a, b) => a + b, 0);
console.log(sum(...numbers)); // Output: 6