Skip to content
Advertisement

Reduce throws “NaN” in JavaScript?

I am trying to sum items in array. While searching Google and Stack Overflow I found that reduce is a good way of summing an array items. But, when there isn’t any key value pair reduce throws error as “Nah”, so how to deal with it?

My array exam:

JavaScript

So from above, I need to calculate all the key values including pair. But when I use it on reduce it gives NaN as the second object doesn’t have ‘pair’,

How to deal this?

My code:

JavaScript

So how to handle this “NaN”

Advertisement

Answer

You could use the new nullish coalescing operator, or since you know these are either numbers or non-existent and you want to us 0 in the non-existent case, the logical || operator:

JavaScript

You don’t need all of those (), though:

JavaScript
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement