Sum of Numbers in an Array

easy
By FrontendAtlas Editorial · Updated Oct 10, 2026
Sum only numeric values from an input array, ignoring non-numbers and NaN. This reinforces safe type checking, accumulator patterns, and the idea that you shouldn’t coerce strings like '5' into numbers unless the problem explicitly asks for it.

Arguments

  • arr: any[] — An array containing numbers and possibly other types (e.g., strings, booleans, nulls). Only actual numbers should be summed.

Returns

number — The sum of all numeric (non-NaN) elements in the array. Returns 0 if there are no numeric entries.

Solution idea

Iterate through the array, accumulate only valid numbers, and skip everything else. The key is to use typeof === 'number' and Number.isNaN so that NaN doesn’t poison the sum and strings/booleans aren’t implicitly coerced.

Examples
// Basic examples

sum([1, 2, 3]) // => 6

// '20' is a string → ignored

sum([10, '20', 30]) // => 40

// Ignores non-numbers

sum(['a', 5, true, 7]) // => 12

// Handles empty array

sum([]) // => 0