Rest parameters

In ES5, inside a function body, you can use the arguments object to iterate the parameters of the function. In ES6, you can use rest parameters syntax to define an indefinite number of arguments as an array.

Let's see the following example:

1.  // Using arguments in ES5
2. function workout(exercise1) {
3. var todos = Array.prototype.slice.call(arguments,
workout.length);
4. console.log('Start from ' + exercise1);
5. console.log(todos.length + ' more to do');
6. }
7. // equivalent to rest parameters in ES6
8. function workout(exercise1, ...todos) {
9. console.log('Start from ' + exercise1); // Start from
//Treadmill
10. console.log(todos.length + ' more to do'); // 2 more to do
11. console.log('Args length: ' + workout.length); // Args length: 1
11. }
12. workout('Treadmill', 'Pushup', 'Spinning');

In line 8, we define a rest parameter todos. It is prefixed with three dots and is the last named parameter of the workout() function. To archive this in ES5, as you can see in line 3, we need to slice the arguments object. And in line 11, you can see that the rest parameter todos does not affect the length of the argument in the workout () function.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.148.104.242