Practice
JavaScriptData StructuresReactConcepts
Sign in
← Back to problems

Sum of an Array

Working With Arrayseasy

Course · Section 11: Working With Arrays · Lecture 149: Simple Array Methods

Implement `sum(arr)` that returns the sum of all numbers in `arr`. Return `0` for an empty array.

Sample tests

Input: sum([1,2,3])
Output: 6
Input: sum([])
Output: 0

+ 2 hidden tests run on Submit.

Hints

Common pitfalls
  • Omitting the initial value breaks on an empty array.

Learning resources

  • MDN: Array.prototype.reduce
Approach & explanation (try first)

reduce with an initial 0 sums every element, returning 0 for an empty array.

Loading...
⌘/Ctrl + Enter

Run your code to see results.