4

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();
 });
Akshay
  • 3,361
  • 1
  • 21
  • 19
user3104669
  • 67
  • 1
  • 2
  • 6

3 Answers3

9

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
TimWolla
  • 31,849
  • 8
  • 63
  • 96
7

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.

adeneo
  • 312,895
  • 29
  • 395
  • 388
4
var result = average();
result = (isNaN(result) ? 0 : result); //ternary operator check the number is NaN if so reset the result to 0

Use isNaN function.

Triode
  • 11,309
  • 2
  • 38
  • 48