Compute the sum of elements of an array which can be null or undefined JavaScript

When working with arrays containing numbers, null, and undefined values, we need to compute sums while treating these falsy values as zero. This is a common scenario when processing data from APIs or user inputs.

Let's say we have an array of arrays, each containing some numbers along with some undefined and null values. We need to create a new array that contains the sum of each corresponding sub-array elements, treating undefined and null as 0.

Following is the sample array:

const arr = [[
    12, 56, undefined, 5
], [
    undefined, 87, 2, null
], [
    3, 6, 32, 1
], [
    undefined, null
]];

Using forEach and reduce

We can iterate through each sub-array and use reduce() to sum the elements:

const arr = [[
    12, 56, undefined, 5
], [
    undefined, 87, 2, null
], [
    3, 6, 32, 1
], [
    undefined, null
]];

const newArr = [];
arr.forEach((sub, index) => {
    newArr[index] = sub.reduce((acc, val) => (acc || 0) + (val || 0), 0);
});

console.log(newArr);
[ 73, 89, 42, 0 ]

Using map Method (Alternative)

A more functional approach using map():

const arr = [[
    12, 56, undefined, 5
], [
    undefined, 87, 2, null
], [
    3, 6, 32, 1
], [
    undefined, null
]];

const sums = arr.map(subArray => 
    subArray.reduce((acc, val) => acc + (val || 0), 0)
);

console.log(sums);
[ 73, 89, 42, 0 ]

How It Works

The expression (val || 0) converts null and undefined to 0 because:

  • null || 0 returns 0
  • undefined || 0 returns 0
  • Any number || 0 returns the number itself

Handling Edge Cases

For more robust handling of edge cases like empty arrays:

const arrWithEmpty = [
    [12, 56, undefined, 5],
    [], // empty array
    [null, undefined],
    [10, 20, 30]
];

const safeSums = arrWithEmpty.map(subArray => 
    subArray.length === 0 ? 0 : subArray.reduce((acc, val) => acc + (val || 0), 0)
);

console.log(safeSums);
[ 73, 0, 0, 60 ]

Conclusion

Use reduce() with (val || 0) to safely sum arrays containing null and undefined values. The map() method provides a cleaner functional approach than forEach().

Updated on: 2026-03-15T23:18:59+05:30

838 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements