Introduction

Both the spread operator and the rest operator look exactly the same in JavaScript. This can be confusing if you don’t know the difference between these two operators.

In this article, we will learn about the differences between these operators with some practical examples. Let’s get right into it.

Rest parameters

Rest parameters help us to pass an infinite number of function arguments.

Here is an example:

function sum(a,b,...remaining){
     console.log(a);
     console.log(b);
     console.log(remaining);
}
sum(1,2,3,4,5,6);

// a => 1
// b => 2
// ...remaining => [3,4,5,6]

In the above example, the arguments a and b refer to 1 and 2 while the rest parameter …remaining refers to everything we passed after 1 and 2. The rest parameter in this example is represented as an array [3,4,5,6] when calling the function.

So we are using the rest operator to extract all the remaining array values and put them in an array.

#web-development #coding #javascript #programming

The Difference Between The Spread Operator and The Rest Operator
4.45 GEEK