7.5 Ways To Use The Spread Operator In JavaScript.
Spread operator goes beyond spreading arrays
2 min readOct 12, 2023
The spread operator (...
) is quite versatile and goes beyond just spreading arrays. I will show you various ways to leverage the spread operator.
Copying Arrays
It makes array copying concise and efficient. It creates a new array with the same elements, ensuring that changes to one array don’t affect the other.
const originalArray = [1, 2, 3];
const copiedArray = [...originalArray];
console.log(copiedArray); // Output: [1, 2, 3]
Merging Arrays
Combine arrays effortlessly by spreading their elements into a new array. This method is a cleaner alternative to methods like concat()
.
const array1 = [1, 2, 3];
const array2 = [4, 5, 6];
const mergedArray = [...array1, ...array2];
console.log(mergedArray); // Output: [1, 2, 3, 4, 5, 6]
Copying Objects
It also allows you to create a shallow copy of an object. Remember, this is a shallow copy, and nested objects will still reference the same memory.
const originalObject = { name: 'John', age: 25 };
const copiedObject = { ...originalObject };
console.log(copiedObject); // Output: { name…