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();
 });
                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
isNaNfunction,Number.isNaNdoesn'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 toNaN, but aren't actually the same value asNaN. This also means that only values of the typenumber, that are alsoNaN, returntrue.
Compare:
isNaN("a"); // true
Number.isNaN("a"); // false
                        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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With