JS Built-ins
← Array97 / 226
ArrayArray.prototype.forEachbeginner

Array.prototype.forEach() β€” sum array elements

πŸ“– Usage Example
let total = 0
[10, 20, 30].forEach(n => { total += n })
total  // β†’ 60

Use forEach() to iterate over elements and accumulate a value in an outer variable.

Array.prototype.forEach()

Array.prototype.forEach(callback) executes a provided function once for each array element, in order. Unlike map or filter, it always returns undefined and is used exclusively for side effects.

Challenge: Implement sumArray(nums) that uses forEach to sum all numbers by accumulating into an external variable.

sumArray([1, 2, 3, 4]) // β†’ 10
sumArray([])            // β†’ 0
πŸ’‘ Hints (2)
  • β€’ Declare `let sum = 0` before `forEach`, then add each element inside the callback.
  • β€’ `forEach` does not return anything useful β€” the side effect is the mutation of `sum`.