Spread and Rest Operators in Simple words๐Ÿ˜ƒ

Spread and Rest Operators in Simple words๐Ÿ˜ƒ

ยท

2 min read

Hi Developers , Today we will discuss Spread and Rest Operator and the difference between them.

The syntax used for both the operators is the same i.e (...) but its usage at different places defines spread and rest.

The main difference between the two is that the spread operator is used when we want to spread out values/elements from an array. Rest operator is used at that place where we have to pass unlimited values into an array.

Don't worry if you didn't understand. After going through examples, you will be all clear.

let array= [1,2,3,4,5];

function sum(a,b){
    return a+b;
}

console.log(sum(array)); // 1,2,3,4,5undefined
console.log(sum(1,2,3)); // 3

As you can see in the above example, the function needs individual values but we are passing an array and the output is ๐Ÿฅด. Also, it goes 3 when we are passing three arguments. To solve this problem, spread comes into the picture.

Spread Operator

let array= [1,2,3,4,5];

function sum(a,b){
    return a+b;
}

console.log(sum(...array)); // 3

Here, the elements 1 and 2 comes out from the array and are passed into the sum function and we got 3. We can sum more than 2 values just by increasing the parameters of the function.

But is there any way where we pass the unlimited parameters we want and we get the sum? Yes ๐Ÿ˜Ž, now rest comes into the picture.

Rest Operator

function sum(...array){
    let max= 0;
    for(i of array){
        max+= i;
    }
    return max;
}

console.log(sum(1,2,3,4,5,6,7)); // 28

Here, we are not restricted by the number of arguments, as much as the arguments we give, we get a sum of all the values using the Rest operator.

Thanks for Reading, Happy Learning. ๐Ÿ™‚

ย