JavaScript Rest and Spread Operator {...}

JavaScript Rest and Spread Operator {...}

ยท

2 min read

WHY A NEW CONCEPT?? ๐Ÿค”

You might be questioning yourself about "Rest" and "Spread".Again new concept in JavaScript why? And the simple, sort and sweet answer is to make your life easier instead of using long and n number of lines of code ES6 has made everything short and crisp so that we can write code in short.

Disclaimer: Before the concept starts I would like to tell you, in the beginning, that ...(three dots) are for both rest and spread operator, and they both are not the same as you think.

Getting Started with Modern JavaScript โ€” Spread vs Rest - JavaScript inDepth

SO WHAT'S THE DIFFERENCE?

Rest Operator

"Rest of all"

The Rest Operator is used to put the "rest of some values" in the JavaScript array.

  • It can only be used before the last parameter.

  • It can't be used inside the "use strict" function containing the rest parameter. We can use "use strict" outside the function.

Example:

const restParameterfunc =(fname,lname, ...otherInfo)=>{
    console.log(otherInfo);
}
restParameter("Vatsal","Singh","Male","Web developer")
//Output: ["Male","Web developer"]

In the above function restParameterfunc we have passed four arguments to a function.

i.e fname=Vatsal ,lname=Singh and the remaining got assinged to otherInfo.

Spread Operator

The Spread operator is just opposite the rest operator. Which means it uses to expand the elements.

const myName=["Singh","is","my"];
const aboutMe=["Vatsal", ...myName,"name"];
console.log(aboutMe)

//["Vatsal","Singh","is","my","name"]

So over here we can see that the elements in myName are being copied in aboutMe and can be used again.

To keep in mind:

  • It can't expand object literal {}.

  • Does not clone identical properties.

ย