How to use the spread and rest operator

Nihar Raote
Mar 8 · 3 min read
Spread and rest operators introduced in ES6

Introduction

The aim of this article is to guide you on using the spread and rest operators, one of the advanced features introduced in ES6. The spread and rest operator allow us to spread out and combine multiple elements respectively. Both of them are denoted by 3 periods .... Even though they might look the same, they work differently. While the spread operator expands an array, object, string or any other iterable, the rest parameter, however, does the exact opposite - it combines multiple elements together into an iterable.

How to use them?

Let’s see the use of the spread operator via some examples -

Result without using spread operator
Array destructuring using rest operator
Object destructuring
Result of object destructuring

Where to use them?

We’ve seen how the spread and rest operators are used. We can use the spread operator to efficiently split arrays, objects, and strings. Splitting up a string into characters has become easier. Working with objects has become hassle-free. Be it copying, cloning or concatenating, the spread operator makes it easy to work with arrays and objects.

Variable function arguments handled with rest parameter

Conclusion

The rest and spread operators, in my opinion, are one of the best features of ES6 along with Promises. They offer a lot of benefits to using them in addition to making the code more readable. If you haven’t used them yet, what are you waiting for?


Nihar Raote

Written by

Front-end developer. Self learning programmmer. Currently learning web development. Also interested in web design