2018-09-30 23:01:58 +01:00
---
id: 587d7b88367417b2b2512b47
2019-05-08 10:30:24 -04:00
title: Use the Rest Parameter with Function Parameters
2018-09-30 23:01:58 +01:00
challengeType: 1
---
## Description
< section id = 'description' >
2019-05-08 10:30:24 -04:00
In order to help us create more flexible functions, ES6 introduces the < dfn > rest parameter< / dfn > for function parameters. With the rest parameter, you can create functions that take a variable number of arguments. These arguments are stored in an array that can be accessed later from inside the function.
2018-09-30 23:01:58 +01:00
Check out this code:
2019-05-17 06:20:30 -07:00
```js
function howMany(...args) {
return "You have passed " + args.length + " arguments.";
}
console.log(howMany(0, 1, 2)); // You have passed 3 arguments.
console.log(howMany("string", null, [1, 2, 3], { })); // You have passed 4 arguments.
```
2019-05-08 10:30:24 -04:00
The rest parameter eliminates the need to check the < code > args< / code > array and allows us to apply < code > map()< / code > , < code > filter()< / code > and < code > reduce()< / code > on the parameters array.
2018-09-30 23:01:58 +01:00
< / section >
## Instructions
< section id = 'instructions' >
2018-11-27 02:05:14 +05:30
Modify the function < code > sum< / code > using the rest parameter in such a way that the function < code > sum< / code > is able to take any number of arguments and return their sum.
2018-09-30 23:01:58 +01:00
< / section >
## Tests
< section id = 'tests' >
```yml
2018-10-04 14:37:37 +01:00
tests:
2018-10-20 21:02:47 +03:00
- text: The result of < code > sum(0,1,2)</ code > should be 3
2019-03-25 19:49:34 +05:30
testString: assert(sum(0,1,2) === 3);
2018-10-20 21:02:47 +03:00
- text: The result of < code > sum(1,2,3,4)</ code > should be 10
2019-03-25 19:49:34 +05:30
testString: assert(sum(1,2,3,4) === 10);
2018-10-04 14:37:37 +01:00
- text: The result of < code > sum(5)</ code > should be 5
2019-03-25 19:49:34 +05:30
testString: assert(sum(5) === 5);
2018-10-04 14:37:37 +01:00
- text: The result of < code > sum()</ code > should be 0
2019-03-25 19:49:34 +05:30
testString: assert(sum() === 0);
- text: The < code > sum</ code > function should use the < code > ...</ code > rest parameter on the < code > args</ code > parameter.
testString: assert(code.replace(/\s/g,'').match(/sum=\(\.\.\.args\)=>/));
2018-09-30 23:01:58 +01:00
```
< / section >
## Challenge Seed
< section id = 'challengeSeed' >
< div id = 'js-seed' >
```js
2019-03-25 19:49:34 +05:30
const sum = (x, y, z) => {
2019-03-29 09:36:58 -07:00
const args = [x, y, z];
2019-03-25 19:49:34 +05:30
return args.reduce((a, b) => a + b, 0);
}
2018-09-30 23:01:58 +01:00
console.log(sum(1, 2, 3)); // 6
```
< / div >
< / section >
## Solution
< section id = 'solution' >
```js
2019-03-25 19:49:34 +05:30
const sum = (...args) => {
return args.reduce((a, b) => a + b, 0);
}
2018-09-30 23:01:58 +01:00
```
< / section >