Rest and Spread operator in JS

·

2 min read

What is Spread operator

Spread operator is use to divide array elements or object properties inside new array or new object so that elements of object can be inserted or deleted Example

      const myPot = ['Rudra', 'Kasi', 'Masi'];
      const newPot = [...myPot, 'Khwaja'];
      console.log(newPt);

      Output:

      [“Rudra”, “Kasi”, “Masi”, “Khwaja”]

An object example of using spread operator

          const firstobject = {
            id: 1,
            firstnName:'Kurd'
          }
          const updatedObject = {
            ...firstObject,
            lastName: 'Madridsta'
          }
          console.log(updatedStudent);

          Output:

          {id: 1, firstnName: “Kurd”, lastName: “Madridsta”}

Using Spread Operator In function Calls

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

        const nums = [1,2,3];

        sum(...nums) // 6

Using spread operator as function parameter while calling the function divides the array elements individually and pass them on sum function where it is summed up

Rest Operator

rest operator is used for merging list of functional arguments into an array we use this when we dont know how many arguments need to be passed to our function

rest means rest of the elements

function sumofAll(...inputs){

console.log(inputs)//it will give you in the form of an array //console.log(...inputs)//it will give you direct values

//Now we have to add

let total = 0; for (let i of inputs){ total=total+i; } console.log(total); } sum(1,2,3,4,5,6,7,8,9,10)

rest operator can accept any no of arguments as it wants rest operator will take all of them and perform certain actions

Limitatations

You can use them max once in a function, multiple rest parameters are not allowed.