Here are 6 ways to use the Spread operator with Array in JavaScript. You can use it to merge or clone an array. Or use it to convert iterables to an array.

// Merge Array
[...array1, ...array2]

// Clone Array
[...array]

// Sting → Array
[...'string']

// Set  → Array
[...new Set([1,2,3])]

// Node List → Array
[...nodeList]

// Arguments → Array
[...arguments]

Understanding Spread

MDN: Spread syntax allows an iterable such as an array expression or string to be expanded in places where zero or more arguments (for function calls) or elements (for array literals) are expected, or an object expression to be expanded in places where zero or more key-value pairs (for object literals) are expected.

Clear as mud right 😂 Spread took me a long time to understand. So let me try to explain with 2 analogies that helped me. Hopefully, it can also help you 🤞

Spread is like Russian Dolls

The spread syntax takes your array and expands it into elements. Imagine your array is like those Russian Dolls. When you call the spread syntax on it, it will take the nested individual doll out and lay it out in its own individual pieces.

Credit: Wikipedia

Spread is like an Eraser

If the Russian Dolls analogy didn’t help and Spread is still muddy for you 😵 In that case, just think of the ... syntax as an eraser that removes the brackets of the array 😂

[
  ...[1, 2, 3] // 👈 The dots erases the brackets
]

/*  Becoming this: */
[
  1, 2, 3 // 👈 "Erased"
]

Array Manipulation

The best thing about the Spread syntax is to use it for array manipulation 👏

#javascript #developer

6 Use Case of Spread with Array in JavaScript
27.70 GEEK