The ES6 (ECMAScript 2015) spread operator is a powerful feature in JavaScript that allows you to expand or spread elements from an array or object into another array or object. It is represented by three consecutive dots (...
). Here’s a breakdown of how it works and some common use cases:
1. Spreading Elements in Arrays
You can use the spread operator to spread elements of an existing array into a new array.
const fruits = ['apple', 'banana', 'cherry'];
const moreFruits = ['orange', ...fruits, 'mango'];
console.log(moreFruits);
// Output: ['orange', 'apple', 'banana', 'cherry', 'mango']
In this example, the ...fruits
spreads out the elements of the fruits
array into the moreFruits
array.
2. Copying Arrays
The spread operator is often used to create a shallow copy of an array.
Example:
const originalArray = [1, 2, 3];
const copiedArray = [...originalArray];
console.log(copiedArray);
// Output: [1, 2, 3]
3. Spreading Elements in Function Calls
You can use the spread operator to pass elements of an array as individual arguments to a function.
Example:
const numbers = [1, 2, 3];
const sum = (a, b, c) => a + b + c;
console.log(sum(...numbers));
// Output: 6
Here, ...numbers
spreads the array elements as individual arguments to the sum
function.
4. Combining Arrays
You can use the spread operator to combine multiple arrays into one.
Example:
const array1 = [1, 2];
const array2 = [3, 4];
const combinedArray = [...array1, ...array2];
console.log(combinedArray);
// Output: [1, 2, 3, 4]
5. Spreading Properties in Objects
The spread operator can also be used to spread properties from one object into another. This is especially useful for creating new objects based on existing ones.
Example:
const person = { name: 'John', age: 30 };
const job = { title: 'Developer', company: 'XYZ Corp' };
const personWithJob = { ...person, ...job };
console.log(personWithJob);
// Output: { name: 'John', age: 30, title: 'Developer', company: 'XYZ Corp' }
6. Merging Objects
You can use the spread operator to merge objects, where properties from later objects will overwrite properties from earlier ones if they have the same key.
Example:
const obj1 = { a: 1, b: 2 };
const obj2 = { b: 3, c: 4 };
const mergedObj = { ...obj1, ...obj2 };
console.log(mergedObj); // Output: { a: 1, b: 3, c: 4 }
In this case, the value of b
in obj2
overrides the value of b
in obj1
.
The spread operator is a versatile tool that simplifies many common programming tasks related to arrays and objects.