Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
April 25, 2022 01:56 am GMT

The Rest and the Spread operator of JS

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:

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:

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?

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?

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.

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.

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.

const obj = {    "hello" : "world",    "foo" : "bar"}console.log(obj)  // { hello: 'world', foo: 'bar' }console.log(...obj)  // TypeError: Found non-callable @@iteratorconsole.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.

// Creating arrayconst arr = [1,2,3];console.log([...arr, 4,5]);  // [ 1, 2, 3, 4, 5 ]// Creating Objectconst 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.


Original Link: https://dev.to/umangm05/the-rest-and-the-spread-operator-of-js-8an

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To