ES6 Rest ParameterThe rest parameter is introduced in ECMAScript 2015 or ES6, which improves the ability to handle parameters. The rest parameter allows us to represent an indefinite number of arguments as an array. By using the rest parameter, a function can be called with any number of arguments. Before ES6, the arguments object of the function was used. The arguments object is not an instance of the Array type. Therefore, we can't use the filter() method directly. The rest parameter is prefixed with three dots (...). Although the syntax of the rest parameter is similar to the spread operator, it is entirely opposite from the spread operator. The rest parameter has to be the last argument because it is used to collect all of the remaining elements into an array. SyntaxExampleOutput Sum = 60 All the arguments that we have passed in the function will map to the parameter list. As stated above, the rest parameter (...) should always be at last in the list of arguments. If we place it anywhere else, it will cause an error. The rest parameter with the following syntax will cause an error. Difference between Rest Parameter and arguments objectThe rest parameter and arguments object are different from each other. Let's see the difference between the rest parameter and the arguments object:
Rest Parameters and DestructuringDestructuring means to break down a complex structure into simpler parts. We can define an array as the rest parameter. The passed-in arguments will be broken down into the array. Rest parameter supports array destructuring only. By using the rest parameter, we can put all the remaining elements of an array in a new array. Let's see an illustration of the same. ExampleOutput Violet Indigo [ 'Blue', 'Green', 'Yellow', 'Orange', 'Red' ] Rest Parameter in a dynamic functionJavaScript allows us to create dynamic functions by using the function constructor. We can use the rest parameter within a dynamic function. ExampleOutput [ 10, 20, 30 ] Next TopicES6 Variables |