• Post category:JavaScript
  • Reading time:4 mins read

In this article, we will explain you about the ES6 Rest Parameter in JavaScript.

Newbie developers might be not aware of the rest parameters. So here we will so you how to use it and in which condition we can use and also we need to take care of few points while using it.

We can say that rest parameter collects all remaining elements into an array. This is something called destructuring which is breaking an array or object into smaller pieces.

Table of Contents: Rest Parameters in JavaScript

  1. Declare rest parameter in object
  2. Declare rest parameter in function parameters
  3. Error while wrong declaration of rest parameters

1. Declare rest parameter in object

If you have an object where you want to grab the single attributes value and rest of all the attributes in other variable then you can declare the rest parameter.

Look at the following example.

const obj = {foo: 1, bar: 2, baz: 3};
const {bar, ...rest} = obj;

console.log(bar); // Output: 2
console.log(rest); // Output: {foo: 1, baz: 3}

In the above example, we have one object that contains multiple attributes. From where we fetched only bar attribute and rest of all the attributes we fetched in rest attribute.

2. Declare rest parameter in function parameters

In such case, if you are not sure about the parameters of the function arguments then you can use the rest parameter.

function func(param1, param2, ...rest) {
   console.log(param1); // Output: "foo"
   console.log(param2); // Output: 25
   console.log(rest); // Output: ["test", 28]
}
func("foo", 25, "test", 28);

Here you can see, we passed the 4 parameters in function and we handle it by rest parameter so we received the last two parameters in type of array.

3. Error while wrong declaration of rest parameters

// ERROR
const {...rest, foo} = obj; // SyntaxError
const {foo, ...rest1, ...rest2} = obj; // SyntaxError

That’s it for today. Happy Coding!

Leave a Reply