freeCodeCamp/curriculum/challenges/english/02-javascript-algorithms-and-data-structures/es6/use-the-rest-parameter-with-function-parameters.english.md
Deanna Tran 338d7ee8a7 Change "rest operator" to say "rest parameter" in challenges and guide (#35496)
* change es6 challenges rest operator to param

* fix rest parameter typos

* change rest operator to parameter in guide

* fix casing

* change rest operator to rest parameter in guide

* change rest operator to rest parameter in curriculum

* remove extra whitespace

* remove whitespaces

* remove whitespace

* fix: removed arabic file

* fix: removed chinese file
2019-05-08 16:30:24 +02:00

2.2 KiB

id, title, challengeType
id title challengeType
587d7b88367417b2b2512b47 Use the Rest Parameter with Function Parameters 1

Description

In order to help us create more flexible functions, ES6 introduces the rest parameter 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. Check out this code:
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.
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.

Tests

tests:
  - text: The result of <code>sum(0,1,2)</code> should be 3
    testString: assert(sum(0,1,2) === 3);
  - text: The result of <code>sum(1,2,3,4)</code> should be 10
    testString: assert(sum(1,2,3,4) === 10);
  - text: The result of <code>sum(5)</code> should be 5
    testString: assert(sum(5) === 5);
  - text: The result of <code>sum()</code> should be 0
    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\)=>/));

Challenge Seed

const sum = (x, y, z) => {
  const args = [x, y, z];
  return args.reduce((a, b) => a + b, 0);
}
console.log(sum(1, 2, 3)); // 6

Solution

const sum = (...args) => {
  return args.reduce((a, b) => a + b, 0);
}