DEV Community

FADHILI Josue
FADHILI Josue

Posted on • Updated on

Unveiling JavaScript Tricks: Dots and spreading well explained with examples

JavaScript Spread Operator: Unraveling the Dots

This article contains examples and explanations of the JavaScript spread operator, a powerful feature that allows for easy expansion of arrays, strings, and objects. In this article, we'll explore various use cases and delve into the intricacies of spreading in JavaScript.

Table of Contents

Interesting examples could be composed with spreading of arrays. Consider this:

[...[..."..."]].length; // -> 3
Enter fullscreen mode Exit fullscreen mode

💡 Explanation:

Why 3? When we use the spread operator, the @@iterator method is called, and the returned iterator is used to obtain the values to be iterated. The default iterator for string spreads a string into characters. After spreading, we pack these characters into an array. Then we spread this array again and pack it back to an array.

A '...' string consists with three . characters, so the length of resulting array is 3.

Now, step-by-step:

[...'...']             // -> [ '.', '.', '.' ]
[...[...'...']]        // -> [ '.', '.', '.' ]
[...[...'...']].length // -> 3
Enter fullscreen mode Exit fullscreen mode

Obviously, we can spread and wrap the elements of an array as many times as we want:

[...'...']                 // -> [ '.', '.', '.' ]
[...[...'...']]            // -> [ '.', '.', '.' ]
[...[...[...'...']]]       // -> [ '.', '.', '.' ]
[...[...[...[...'...']]]]  // -> [ '.', '.', '.' ]
// and so on …
Enter fullscreen mode Exit fullscreen mode

Using Spread Operator with Arrays

Spreading in JavaScript allows us to easily expand arrays into individual elements. It's a powerful feature that can lead to some fascinating results. Let's explore some interesting examples.

const numbers = [1, 2, 3, 4, 5];
const sum = (...args) => args.reduce((acc, val) => acc + val, 0);
const result = sum(...numbers); // 15

const arr1 = ['a', 'b', 'c'];
const arr2 = [...arr1, 'd', 'e', 'f']; // [ 'a', 'b', 'c', 'd', 'e', 'f' ]

Enter fullscreen mode Exit fullscreen mode

Spreading Strings

The spread operator (...) is a versatile feature in JavaScript that allows us to easily manipulate strings. Let's explore some examples:

const str = "Spread";
const spreadChars = [...str].map(char => char.toUpperCase());  // [ 'S', 'P', 'R', 'E', 'A', 'D' ]
Enter fullscreen mode Exit fullscreen mode

Combining Spread with Objects

const obj1 = { foo: 'bar', x: 42 };
const obj2 = { foo: 'baz', y: 13 };

const combined = { ...obj1, ...obj2 }; // { foo: 'baz', x: 42, y: 13 }

Enter fullscreen mode Exit fullscreen mode

The spread operator provides a concise and powerful way to manipulate arrays, strings, and objects in JavaScript. By understanding its versatility, you can write more expressive and efficient code.

Top comments (0)