Function with Rest Parameters in JavaScript

Level 3136 keystrokes

Uses rest parameters to accept any number of arguments and sum them.

JavaScript code

// ...numbers collects all arguments into an array
1function sum(...numbers) {
// reduce() accumulates values: acc starts at 0, adds each n
// Returns the total sum of all numbers
2 return numbers.reduce((acc, n) => acc + n, 0);
3}
// Call with 3 arguments: 1 + 2 + 3 = 6
4console.log(sum(1, 2, 3));
// Call with 4 arguments: 10 + 20 + 30 + 40 = 100
5console.log(sum(10, 20, 30, 40));

Output

6
100
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this JavaScript code and how often they appear.

  • ,× 7
  • (× 7
  • )× 7
  • .× 6
  • ;× 3
  • {× 1
  • }× 1
  • +× 1
  • =× 1
  • >× 1

More JavaScript examples at level 3

← JavaScript typing practice