Array Reduce in JavaScript

Level 392 keystrokes

This uses reduce to calculate the sum of all numbers in the array.

JavaScript code

// Create an array of numbers
1let nums = [1, 2, 3, 4, 5];
// reduce() folds the array into one value: acc is the running total, n the current element
// 0 is the initial value of acc
2let sum = nums.reduce((acc, n) => acc + n, 0);
// Step by step: 0+1=1, 1+2=3, 3+3=6, 6+4=10, 10+5=15
3console.log(sum);

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
  • ;× 3
  • (× 3
  • )× 3
  • =× 3
  • .× 2
  • [× 1
  • ]× 1
  • +× 1
  • >× 1

More JavaScript examples at level 3

← JavaScript typing practice