Change NaN to 0 in Javascript

I have code that returns me the result of the middle javascript function in bootstrap modal. But when one of the inputs is empty, it returns NaN. How can I change NaN to 0?

Here is my code that returns the result:

 $(".average").click(function () {
 var result = average();
 $("#myModal .modal-body h2").text(result);
 $("#myModal").modal();
 });
+4
source share
3 answers

You can check if there is a value NaNusing the function isNaN:

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

In the future, when ECMAScript 6 will be widely available, you might consider switching to Number.isNaN, because it does isNaNnot properly treat strings as parameters.

isNaN, Number.isNaN . , , NaN, , NaN. , number, NaN, true.

:

isNaN("a"); // true
Number.isNaN("a"); // false
+7

OR, ""

var result = average() || 0;

as null, undefined NaN - , 0, , 0 return 0, .

+6
var result = average();
result = (isNaN(result) ? 0 : result); //ternary operator check the number is NaN if so reset the result to 0

isNaN.

+3
source

Source: https://habr.com/ru/post/1525615/


All Articles