Array Reduce Sum in JavaScript

Level 3107 keystrokes

reduce() accumulates array values into a single result. Here it calculates the sum.

JavaScript code

// Define a function that takes an array as parameter
1function sum(arr) {
// reduce() adds each num to the running total
// total starts at 0, the second argument
2 return arr.reduce((total, num) => total + num, 0);
3}
// Call the function with an array and print the result (15)
4console.log(sum([1, 2, 3, 4, 5]));

Output

15
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.

  • ,× 6
  • (× 5
  • )× 5
  • ;× 2
  • .× 2
  • [× 1
  • ]× 1
  • {× 1
  • }× 1
  • +× 1

More JavaScript examples at level 3

← JavaScript typing practice