The Rest and the Spread operator of JS
Tags: javascript, programming, tutorial, beginners
Published: 2022-04-25 01:56:41

Hello folks! I hope you are all doing great.
Ever heard developers talking about "spread" operators or just saw "..." [Triple Dots] in JS code and wondered what is this thing.
Well, we're going to cover that today.

The syntax of rest and spread operator looks exactly the same but they are polar opposite of each other in terms of functionality.

Let's look at both of them one by one.

## The Rest operator
The rest operator is used to take an indefinite number of arguments in a function and condenses it to an array.
Example:
```javascript
function foo(...bar){
    return bar;
}

console.log(foo(1,2,3,4));  // [ 1, 2, 3, 4 ]
console.log(foo(1,2));  // [ 1, 2 ]
```
Whatever the number of parameters you pass into a function the rest operator collects all the arguments and "condenses" them into an Array which can be useful in a lot of cases.

It can also be used like this:
```javascript
function foo(a,b,...bar){
    console.log(a);  // 1
    console.log(b);  // 2
    console.log(bar);  // [ 3, 4 ]
}

foo(1,2,3,4);
```
What we've done is told the function that we are going to pass "a", "b" and whatever we pass after that, condense it into an array.
Now, you might me thinking of some edge cases like "what will happen if I ... ". Don't worry I am getting on that too.
_What happens if I pass no value for the rest oprator?_

```javascript
function foo(a,b,...bar){
    console.log(a);  // 1
    console.log(b);  // 2
    console.log(bar);  // []
}

foo(1,2);
```
Here, the rest parameter does not gets any value which results in an empty array.

_But, what happens if I shift the rest parameter to the first or the second position?_
```javascript
function zen(a,...bar,b){  // SyntaxError: Rest parameter must be last formal parameter
    console.log(a);
    console.log(b);
    console.log(bar);
}

zen(1,2,3,4);
```
This will not run. The reason is clearly mentioned in the error. 
The rest parameter must be the last function argument.

Now that we know, what is rest operator. Let's look at a use-case.

**Suppose, you were said to create a function that takes two values and returns the sum of them. Easy? isn't it. Let's escalate it, Now you need to create the same function but there could be any possible number of parameters and your function must return the sum of all of the arguments.**

One approach is that you create different functions for different number of parameters. Now that you know the rest operator, you must'nt worry about that.

```javascript
function addValues(...values){
    let sum = 0;
    for(let i = 0; i< values.length;i++){
        sum += values[i]
    }
    return sum;
}

console.log(addValues(1,2,3,4,5))  // 15
```
_Note: I know I could've used foreach or even reduce method to do the same task but to keep this post general for all the people, I used the for loop.Well, another topic for another day._

## The Spread operator
Earlier, I told you that both rest and spread has same syntax and still they are opposites of each other.
Where rest operator takes multiple values and condenses them , the spread opeartor expands the object values.

```javascript
const arr = [1,2,3,4];
console.log(arr);  // [ 1, 2, 3, 4 ]
console.log(...arr);  // 1 2 3 4
```
As you can see the spread operator spreads the value of the array and it also works on the object.

Spread Operator can be used in many different tasks like:

- Copying an array
- Adding to state in React
- Concatenating or combining arrays
- Using Math functions
- Converting NodeList to an array
- Using an array as arguments
- Adding an item to a list
- Combining objects 

The spread works on the objects too.
```javascript
const obj = {
    "hello" : "world",
    "foo" : "bar"
}

console.log(obj)  // { hello: 'world', foo: 'bar' }
console.log(...obj)  // TypeError: Found non-callable @@iterator
console.log({...obj})  // { hello: 'world', foo: 'bar' }
```
You can create a clone of an object and updates it's value with the help of it's key.

```javascript
// Creating array
const arr = [1,2,3];
console.log([...arr, 4,5]);  // [ 1, 2, 3, 4, 5 ]

// Creating Object
const obj = {
    "hello" : "world",
    "foo" : "bar"
};

console.log({...obj, "foo" : "zen"});  // { hello: 'world', foo: 'zen' }
```
## Final Thoughts
The rest parameters and the spread operator has become an integral part of any web project since it's launch. I hope I made both of them clear to you. 
Thanks for reading.

Okay, so that's Umang Mittal signing off.