rest parameter in javascript

rest parameter in javascript

In this tutorial, we will learn about spread operators in javascript.

So let's get started...

What is the rest pattern?

The rest pattern looks exactly the same as the spread operator but it actually does the opposite of the spread operator.

The spread operator is to unpack an array while the rest is to pack element into an array

Basically, Rest parameters collect all the remaining elements into an array.

The Rest element must be last as its name says the rest of the elements

Also,there can be only one rest at a time.

So, seems a bit confusing on how to identify spread operator or rest patterns both have the same syntax, let's clear  this first:

Spread operator stays on the Right side of  =(equal) operator

const arr = [1,2,...[3,4]];

 Rest operator stays on the LEFT side of  =(equal) operator 

const [t,o,...other] = [1,2,3,4,6]


//Output : 1 2 [3, 4, 6]

Use spread and rest operator both at once:

//using spread and rest operator together
const [pizza, , risotto, ...otherFood] = [,,
console.log(pizza, risotto, otherFood);
// Objects
const { sat, ...weekdays } = restaurant.openingHours;

Pass any numbers of arguments into a function:

Suppose We have a function that makes the addition of the multiples the arguments which we pass it and we need to be able to pass it any number of arguments.

Let’s see how we can do this with a rest parameter:

// 2) Functions
const add = function (...numbers) {
  let sum = 0;
  for (let i = 0; i < numbers.length; i++) sum += numbers[i];

add(2, 3);
add(5, 3, 7, 2);
add(8, 2, 5, 3, 2, 1, 4);

const x = [23, 5, 7];
restaurant.orderPizza('mushrooms', 'onion', 'olives', 'spinach');


Thanks for reading.

Do let me know If you face any difficulties please feel free to comment below we love to help you. if you have any feedback suggestion then please inform us by commenting.

Don’t forget to share this tutorial with your friends on facebook, twitter. 

Subscribe to our Newsletter

Stay up to date! Get all the latest posts delivered straight to your inbox.

If You Appreciate What We Do Here On TutsCoder, You Should Consider:

If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.

Support Us

We are thankful for your never ending support.

Leave a Comment