Nishant Girdharwal

Frontend Developer Software Developer || Fascinated by tech trends || Building usable systems that work on web and mobile.

Rest And Spread Operators for Beginners

application-programming-interface

Rest Operators

Collection of remaining elements into an array or an object is known as Rest Operators.

var myName = ["Nishant" , "Shubham" , "Akash"] ;
const [firstName , ...familyName] = myName ;
console.log(firstName); // Nishant ;
console.log(familyName); // [ "Shubham" , "Akash"] ;

In above example, we can see the three dots in line 2 known as the rest operators, is used to collect the all elements of “myName” into a new variable.

If we are using a function and send a number of arguments, then you will receive a function using rest operators as in below example:

function myData(...args){
console.log(args) ; // ["Nishant",30,"UI Developer"]
}
myData("Nishant",30,"UI Developer") ;

Spread Operators

Spread Operator is opposite to Rest Operator , where Rest Operator collects items into an array, the Spread Operator unpacks the collected elements into single elements. We can find the example below:

var myName = ["Nishant" , "Shubham" , "Akash"];
var newArr = [...myName ,"UI" , 30];
console.log(newArr) ; // ["Nishant" , "Shubham" , "Akash" , "UI" , 30 ] ;

The Above example shows that, spread operator is concatenated between 2 arrays and unpacked myName into single elements and, unlike the rest parameter, the spread operator can be the first element, but rest parameter needs to be the last to collect the rest elements .

It can be used to copy one array into another or to concatenate 2 arrays together.

Summary of Rest and Spread Operators

  • Rest Parameter is collecting all remaining elements into an array .
  • Spread Operator is unpacking collected elements such as arrays into single elements .
Share