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
2019-08-05 09:17:33 -07:00
forumTopicId: 301221
2021-01-13 03:31:00 +01:00
dashedName: use-the-rest-parameter-with-function-parameters
2018-09-30 23:01:58 +01:00
---
2020-11-27 19:02:05 +01:00
# --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.
2020-11-27 19:02:05 +01:00
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.
```
2020-11-27 19:02:05 +01:00
The rest parameter eliminates the need to check the `args` array and allows us to apply `map()` , `filter()` and `reduce()` on the parameters array.
# --instructions--
Modify the function `sum` using the rest parameter in such a way that the function `sum` is able to take any number of arguments and return their sum.
2018-09-30 23:01:58 +01:00
2020-11-27 19:02:05 +01:00
# --hints--
The result of `sum(0,1,2)` should be 3
```js
assert(sum(0, 1, 2) === 3);
2018-09-30 23:01:58 +01:00
```
2020-11-27 19:02:05 +01:00
The result of `sum(1,2,3,4)` should be 10
2018-09-30 23:01:58 +01:00
2020-11-27 19:02:05 +01:00
```js
assert(sum(1, 2, 3, 4) === 10);
```
2018-09-30 23:01:58 +01:00
2020-11-27 19:02:05 +01:00
The result of `sum(5)` should be 5
2018-09-30 23:01:58 +01:00
```js
2020-11-27 19:02:05 +01:00
assert(sum(5) === 5);
2018-09-30 23:01:58 +01:00
```
2020-11-27 19:02:05 +01:00
The result of `sum()` should be 0
2018-09-30 23:01:58 +01:00
2020-11-27 19:02:05 +01:00
```js
assert(sum() === 0);
```
The `sum` function should use the `...` rest parameter on the `args` parameter.
2018-09-30 23:01:58 +01:00
2020-11-27 19:02:05 +01:00
```js
assert(__helpers.removeWhiteSpace(code).match(/sum=\(\.\.\.args\)=>/));
```
2018-09-30 23:01:58 +01:00
2020-11-27 19:02:05 +01:00
# --seed--
2018-09-30 23:01:58 +01:00
2020-11-27 19:02:05 +01:00
## --seed-contents--
2018-09-30 23:01:58 +01:00
```js
2020-11-27 19:02:05 +01:00
const sum = (x, y, z) => {
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
```
2019-07-18 08:24:12 -07:00
2020-11-27 19:02:05 +01:00
# --solutions--
```js
const sum = (...args) => {
return args.reduce((a, b) => a + b, 0);
}
```