What is ES6 Triple dots in Javascript? Why you should know about it?


In this article, we are going to discuss a feature introduced in ES6 that is spread operator and rest operator. ? ? ?

What is ES6 Triple dots in Javascript? Why you should know about it?
ES6 Triple dots

I’ve become a big fan of the triple dots that may change your style of solving the problem within JavaScript. We can use triple dots … in two different ways as spread operator and rest operator.

Rest Parameters ?

With rest parameters, we can gather any number of arguments into an array and do what we want with them. Rest parameters have been introduced to reduce the boilerplate code that was induced by the arguments. ?

In myFunc’s last parameter prefixed with … which will cause to all remaining arguments placed within the javascript array.

The rest parameters gather all remaining arguments so there is no sense ? to add rest parameters before the last parameter. The rest parameter must be the last formal parameter.

Rest parameters can be destructured (arrays only), which means that their data can be unpacked into distinct variables.

Spread Operators ✨

The spread operator is used to expand elements of an iterable (like an array) into places where multiple elements can fit.

There have always been a variety of ways to combine arrays, but the spread operator gives use a new method for combining arrays:

With spread operator, Shallow-cloning (excluding prototype) or merging of objects is now possible using a shorter syntax than Object.assign().

? Conclusion

When we see three dots (…) in the code, it’s either rest parameters or the spread operator.

There’s an easy way to distinguish between them:

  1. When three dots (…) is at the end of function parameters, it’s “rest parameters” and gathers the rest of the list of arguments into an array.
  2. When three dots (…) occurs in a function call or alike, it’s called a “spread operator” and expands an array into a list.

Thanks for reading. I hope you like this article feel free to like, comment or share this article with your friends.

? Happy Coding…