DEV Community

Cover image for ES6 for beginners - Part 4 (Rest, Spread)
Łukasz Żarski for 2n IT

Posted on • Edited on

ES6 for beginners - Part 4 (Rest, Spread)

This is the fourth part of ES6 tutorial, created by our dev Bartosz. All of the previous parts you can find here :).

REST

What is rest in ES6? The rest parameter syntax allows us to represent an indefinite number of arguments.
We know that in JavaScript functions can have any number of parameters. Besides, we do not have to give everyone an argument. This was mentioned in JavaScript Part 17.
Now let's say that we have a function that takes an unknown number of parameters for us. Example of simple addition of several arguments by the user when we do not know about its number. Using the standard before ES6, we could do it in the following way.

Since the arguments are not stored in the array but in array-like format, we had to create a new array consisting of arguments. ES6 makes it easy for us to do the job using the rest parameter.

Using the myAdd function, we can add an unlimited number of arguments. The reason for this is that by using the three dots ... and the nameOfparameter, all arguments will be thrown into the array.

Also, we must take care that the rest parameter is used correctly, always at the end of the parameters passed. This is since, it will not just work. The error we receive will certainly remind us of it.

SPREAD

It allows an array of arguments for elements calls (for array 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. Sounds complicated? Let's look at a few examples of how we will use it.

As you can observe with great ease we can combine the arrays.

In the next post, I will talk about array helper methods so stay tuned! Thank's for reading and don't hesitate to express your opinion on this post - all of your feedback will be appreciated :).

Top comments (2)

Collapse
 
b_hantsi profile image
Bala Hantsi 🇳🇬

Nice post, but I couldn't find the previous parts even when I follow the link

Collapse
 
lukaszzarski profile image
Łukasz Żarski

Thank you :). About previous parts - I think that this link might be helpful 2n.pl/blog?tag=ES6 :).