Rest Operator and Spread Operator

Rest Operator and Spread Operator

Rest Operator

Rest operator is used to collect or gather items

Before using the rest we need to follow some specific rules like

  • Placement is must that means you have to place the rest operator the at the end only, otherwise it won't get the result

  • When we talk about the functions we use REST operator when we declare the functions.

The following example can describe all the three things , Arrays, Objects and Functions.

//arrays
const players=["virat","Dhawan","Rohith","sharma"]
const[virat,...restOfPlayers]=players

console.log(virat, restOfPlayers) // virat [ 'Dhawan', 'Rohith', 'sharma' ]
const finalResult=restOfPlayers.find((person)=>person==="sharma")
console.log(finalResult) //sharma

//objects
const footballPlayers={
    Fname:"Christiano",
    Lname:"Ronaldo",
    country:"Portuguese",
    club:"Al Nassr"
}
const{Fname,...listOfFootballPlayers}=footballPlayers
console.log(Fname,listOfFootballPlayers)
//functions
function getAvg(Fname,...rest){
console.log(Fname) //Christiano
console.log(rest) //[ 23, 23, 43, 56, 57 ]
const getAvgResult= rest.reduce((total, current)=>{return total+=current},0)/rest.length
console.log(getAvgResult)
}

getAvg(footballPlayers.Fname,23,23,43,56,57)

Spread Operator

Spread operator allows and iterable to spread or expand the items individually.

split into single items and COPY them.

OR

The spread (...) syntax allows an iterable, such as an array or string, to be expanded in places where zero or more arguments (for function calls) or elements (for array literals) are expected

// This is for Spread Operator
const struct="Structure"
const letters =[...struct]
console.log(letters) //[ 'S', 't', 'r', 'u', 'c', 't', 'u', 'r', 'e' ]
const girls=["mery",'sam','don']

const boys=['ram','krishna','neehal']
const all =[...girls,...boys]
console.log(all) //[ 'mery', 'sam', 'don', 'ram', 'krishna', 'neehal' ]
//Below task for overidng the elements and add new elemnets
const computer={brand:"Dell",country:"America"}

const newComputer ={...computer, brand:"hp" ,name:"Lenovo",cost:10000}

console.log(computer) //{ brand: 'Dell', country: 'America' }
console.log(newComputer) //{ brand: 'hp', country: 'America', name: 'Lenovo', cost: 10000 }

Did you find this article valuable?

Support Venkat Das by becoming a sponsor. Any amount is appreciated!