How to use Spread and Rest Operator in Javascript

Md Shahab Uddin
Plus Marketing
Published in
2 min readDec 26, 2020

Spread and rest operator is one of the coolest features of ECMA6. Using these operators makes our code easy to read and also they are easy to use.

Spread Operator

Spread operator allows iterables(arrays, objects, and strings) to be expanded into single arguments. It’s denoted by three dots(…) followed by the variables or the array/string/object we want to unpack/expand. Let’s see how it works

Write the above code and run it in the console. In the first console, you will get an array as output. But in the second console, you will get only values without an array. Three dots (…) you are watching there is called spread operator. It just unpacks a number of values into individual values.

Spread operator unpacks an array into individual elements.

Let’s see another example

we can see that spread operated expanded the string and array into individual elements.

We can concatenate two arrays with the spread operator

We can copy array using the spread operator in array literals

The good thing about this is that it doesn’t affect the first array.

Same as the above, we can copy objects using the spread operator

We can do array destructuring using the spread operator

spread operator in functions: Let’s see an example from the MDN docs

What happens here is that (…numbers) unpacks the array so that the console interprets it as :

consoel.log(sum(1,2,3))

Rest operator converts an array into parameters

Also, we can use the spread operator in arguments:

Let’s see an example. We will create a function to do addition. We declare a function with three parameters. But if we give it 4 arguments, it will still run but only the first three arguments will be used.

But we can solve this with the spread operator

now you can add unlimited numbers with spread operator. Another use of spread here. Let's look at the image below.

The spread operator also can be used with constructor

Rest Parameter:

Rest operator and Spread operator look the same But a little different.

Spread operators expand an array into parameters. But the Rest operator does the opposite, it collects the parameters and turns them into an array.

We can include in this in function definition just by using three dots(…) followed by the name of the array that will contain them. It means, brings those parameters here and make them an array.

Rest Parameter has to be the last argument.

In this code, we will receive the arguments through the rest parameter

Let’s do addition using the rest parameter

What happens here is that all the arguments we pass here are converted to an array. After that, we run for loop on the array and complete the addition.

Thanks for reading my article. Follow me if you like my articles.

--

--