Rest Parameters in JavaScript
Today we will explain you about the Rest Parameters 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.
Rest Parameters in JavaScript, Rest parameters and spread operator, Javascript's three dots ( ... ): Spread vs rest operators, Understanding the JavaScript Rest Parameter, ES6: What is the difference between Rest and Spread?, rest parameters typescript, rest and spread operator, rest operator in es6.
Checkout more articles on JavaScript/ReactJS
- Arrow Functions in JavaScript
- Object doesn't support property or method ‘includes’ in IE
- Copy text to the Clipboard in ReactJS
- Replace all occurrences of a string in JavaScript
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
- Declare rest parameter in object
- Declare rest parameter in function parameters
- 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 below 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
While we are working with rest parameters, we have to take care of a few points.
- The `...rest` parameter must be the last element.
- Never define multiple `...rest` parameter in single definition
// ERROR
const {...rest, foo} = obj; // SyntaxError
const {foo, ...rest1, ...rest2} = obj; // SyntaxError
That's it for today. Happy Coding!