07 Mar 2024
Intermediate
The spread operator in JavaScript (...), introduced in ECMAScript 6 (ES6), is a shortcut to expand an iterable (like an array or object) into its individual elements. It's useful for copying parts of arrays or objects, or for passing elements as arguments to functions.
Some use cases of the spread operator are:
- Copying Arrays: The spread operator can be used to copy arrays easily without modifying the original array.
const originalArray = [1, 2, 3];
const copyArray = [...originalArray];
- Concatenating Arrays: You can concatenate arrays using the spread operator.
const array1 = [1, 2, 3];
const array2 = [4, 5, 6];
const concatenatedArray = [...array1, ...array2];
- Passing Arrays as Arguments: You can use the spread operator to pass an array as individual arguments to a function.
function myFunction(x, y, z) {
console.log(x, y, z);
}
const args = [0, 1, 2];
myFunction(...args); // Output: 0 1 2
- Combining Objects: You can combine objects into a new object using the spread operator.
const obj1 = { foo: 'bar', x: 42 };
const obj2 = { foo: 'baz', y: 13 };
const combinedObj = { ...obj1, ...obj2 };
- Cloning Objects: You can clone objects using the spread operator.
const originalObj = { name: 'John', age: 30 };
const clonedObj = { ...originalObj };
- Destructuring with Arrays: The spread operator can be used in array destructuring.
const [first, ...rest] = [1, 2, 3, 4, 5];
console.log(first); // Output: 1
console.log(rest); // Output: [2, 3, 4, 5]
- Creating new Arrays: You can use the spread operator to create new arrays with additional elements.
const newArray = [...oldArray, element];
- Converting Iterables to Arrays: You can convert iterables (like strings or NodeLists) into arrays using the spread operator.
const str = 'hello';
const charArray = [...str]; // ['h', 'e', 'l', 'l', 'o']
javascript
spread-operator