The Spread Operator in JavaScript

The spread operator (...) allows an iterable such as an array or string to be expanded in places where zero or more arguments (for function calls) or elements (for array literals) are expected.

Example 1: Merging Arrays

const array1 = [1, 2, 3];
const array2 = [4, 5, 6];
const mergedArray = [...array1, ...array2];
console.log(mergedArray); // Output: [1, 2, 3, 4, 5, 6]

Example 2: Copying Arrays

const originalArray = [1, 2, 3];
const copiedArray = [...originalArray];
console.log(copiedArray); // Output: [1, 2, 3]

Example 3: Spreading Strings

const str = "Hello";
const chars = [...str];
console.log(chars); // Output: ["H", "e", "l", "l", "o"]

Check the console for outputs of the examples above.


View Challenge