Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change NaN to 0 in Javascript [duplicate]

Tags:

javascript

I have a code that return to me result of javascript average function in bootstrap modal. But when one of inputs are blank, he return NaN . How i can change NaN to 0?

Here is my code that return result:

 $(".average").click(function () {
 var result = average();
 $("#myModal .modal-body h2").text(result);
 $("#myModal").modal();
 });
like image 446
user3104669 Avatar asked Dec 01 '22 02:12

user3104669


2 Answers

You can check whether a value is NaN using the isNaN function:

var result = average();
if (isNaN(result)) result = 0;

In the future, when ECMAScript 6 is widely available one may consider switching to Number.isNaN, as isNaN does not properly handle strings as parameters.

In comparison to the global isNaN function, Number.isNaN doesn't suffer the problem of forcefully converting the parameter to a number. This means it is now safe to pass values that would normally convert to NaN, but aren't actually the same value as NaN. This also means that only values of the type number, that are also NaN, return true.

Compare:

isNaN("a"); // true
Number.isNaN("a"); // false
like image 102
TimWolla Avatar answered Dec 04 '22 09:12

TimWolla


Why not just OR, this is one of the most common ways to set a "fallback" value

var result = average() || 0;

as null, undefined and NaN are all falsy, you'd end up with 0, just be aware that 0 is also falsy and would in this case also return 0, which shouldn't be an issue.

like image 35
adeneo Avatar answered Dec 04 '22 11:12

adeneo