The Spread Operator is represented by three dots .... When used, the Spread Operator helps us "expand" an array or object into individual elements. Therefore, we can pass these elements into a new array, combine arrays, or use them as arguments for a function.
Array Copy: With the Spread Operator, we can quickly and easily copy an array.
const numbers = [1, 2, 3];
const copiedNumbers = [...numbers];
console.log(copiedNumbers); // Output: [1, 2, 3]
Array Concatenation: The Spread Operator also allows us to combine multiple arrays into a single array.
const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];
const combinedArray = [...arr1, ...arr2];
console.log(combinedArray); // Output: [1, 2, 3, 4, 5, 6]
Add Element to Array: Using the Spread Operator, we can add one or more elements to an existing array.
const originalArray = [1, 2, 3];
const newArray = [...originalArray, 4, 5];
console.log(newArray); // Output: [1, 2, 3, 4, 5]
The Spread Operator can be used not only with arrays but also with objects. When using the Spread Operator with objects, we can copy the properties of the original object and add new ones or update existing properties.
const person = { name: 'John', age: 25 };
const updatedPerson = { ...person, age: 26, gender: 'Male' };
console.log(updatedPerson);
// Output: { name: 'John', age: 26, gender: 'Male' }
In the example above, we copied the object 'person' and changed the value of the 'age' attribute to 26 and added a new attribute 'gender'.
The Spread Operator is also very useful when passing arguments to a function. With the Spread Operator, we can pass an array into the arguments of a function.
function sum(a, b, c) {
return a + b + c;
}
const numbers = [1, 2, 3];
const result = sum(...numbers);
console.log(result); // Output: 6
In the example above, we passed the array numbers to the sum function using the Spread Operator. The elements in the array will correspond to the arguments of the function.