Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Javascript, how to avoid NaN when adding arrays

I'm trying to add the values of two arrays in javascript eg. [1,2,1] + [3,2,3,4]

The answer should be 4,4,4,4 but I'm either getting 4,4,4 or 4,4,4,NaN if I change the 1st array length to 4.

I know a 4th number needs to be in the 1st array, but i can't figure out how to tell javascript to make it 0 rather then undefined if there is no number.

like image 851
Jonas Avatar asked Dec 11 '09 00:12

Jonas


People also ask

How do I restrict NaN in JavaScript?

In this article, we will convert the NaN to 0. Using isNaN() method: The isNan() method is used to check the given number is NaN or not. If isNaN() returns true for “number” then it assigns the value 0. Using || Operator: If “number” is any falsey value, it will be assigned to 0.

Why am I getting NaN in JavaScript?

The special value NaN shows up in JavaScript when Math functions fail ( Math. sqrt(-37) ) or when a function trying to parse a number fails ( parseInt("No integers here") ). NaN then poisons all other math functions, leading to all other math operations resulting in NaN .

What happens if we add two arrays in JavaScript?

In summary, the addition of arrays causes them to be coerced into strings, which does that by joining the elements of the arrays in a comma-separated string and then string-concatenating the joined strings.


1 Answers

Use isNaN to ensure the value does not evaluate to NaN in arithmetic operations.

This will safely add two numbers such that if one of them is not a number, it will be substituted with 0.

var c = (isNaN(a) ? 0 : a) + (isNaN(b) ? 0 : b);

If you suspect that either a or b could be a string instead of number ("2" instead of 2), you have to convert it into number before adding it. You can use a Unary + to do it.

var c = (isNaN(a) ? 0 : +a) + (isNaN(b) ? 0 : +b);
like image 126
Chetan S Avatar answered Sep 30 '22 14:09

Chetan S