Use the logical OR (||) operator to convert NaN to 0 , e.g. const result = val || 0; . The logical OR (||) operator returns the value to the right if the value to the left is falsy.
In mathematics, zero divided by zero is undefined and is therefore represented by NaN in computing systems.
Unquoted literal constant NaN is a special value representing Not-a-Number. Since NaN always compares unequal to any number, including NaN, it is usually used to indicate an error condition for a function that should return a valid number.
You can do this:
a = a || 0
...which will convert a from any "falsey" value to 0
.
The "falsey" values are:
false
null
undefined
0
""
( empty string )
NaN
( Not a Number )
Or this if you prefer:
a = a ? a : 0;
...which will have the same effect as above.
If the intent was to test for more than just NaN
, then you can do the same, but do a toNumber conversion first.
a = +a || 0
This uses the unary + operator to try to convert a
to a number. This has the added benefit of converting things like numeric strings '123'
to a number.
The only unexpected thing may be if someone passes an Array that can successfully be converted to a number:
+['123'] // 123
Here we have an Array that has a single member that is a numeric string. It will be successfully converted to a number.
Using a double-tilde (double bitwise NOT) - ~~
- does some interesting things in JavaScript. For instance you can use it instead of Math.floor
or even as an alternative to parseInt("123", 10)
! It's been discussed a lot over the web, so I won't go in why it works here, but if you're interested: What is the "double tilde" (~~) operator in JavaScript?
We can exploit this property of a double-tilde to convert NaN
to a number, and happily that number is zero!
console.log(~~NaN); // 0
Write your own method, and use it everywhere you want a number value:
function getNum(val) {
if (isNaN(val)) {
return 0;
}
return val;
}
Something simpler and effective for anything :
function getNum(val) {
val = +val || 0
return val;
}
...which will convert a from any "falsey" value to 0
.
The "falsey" values are:
false
null
undefined
0
""
( empty string )
NaN
( Not a Number )
How about a regex?
function getNum(str) {
return /[-+]?[0-9]*\.?[0-9]+/.test(str)?parseFloat(str):0;
}
The code below will ignore NaN to allow a calculation of properly entered numbers
function getNum(str) {
return /[-+]?[0-9]*\.?[0-9]+/.test(str)?parseFloat(str):0;
}
var inputsArray = document.getElementsByTagName('input');
function computeTotal() {
var tot = 0;
tot += getNum(inputsArray[0].value);
tot += getNum(inputsArray[1].value);
tot += getNum(inputsArray[2].value);
inputsArray[3].value = tot;
}
<input type="text"></input>
<input type="text"></input>
<input type="text"></input>
<input type="text" disabled></input>
<button type="button" onclick="computeTotal()">Calculate</button>
Rather than kludging it so you can continue, why not back up and wonder why you're running into a NaN in the first place?
If any of the numeric inputs to an operation is NaN, the output will also be NaN. That's the way the current IEEE Floating Point standard works (it's not just Javascript). That behavior is for a good reason: the underlying intention is to keep you from using a bogus result without realizing it's bogus.
The way NaN works is if something goes wrong way down in some sub-sub-sub-operation (producing a NaN at that lower level), the final result will also be NaN, which you'll immediately recognize as an error even if your error handling logic (throw/catch maybe?) isn't yet complete.
NaN as the result of an arithmetic calculation always indicates something has gone awry in the details of the arithmetic. It's a way for the computer to say "debugging needed here". Rather than finding some way to continue anyway with some number that's hardly ever right (is 0 really what you want?), why not find the problem and fix it.
A common problem in Javascript is that both parseInt(...)
and parseFloat(...)
will return NaN if given a nonsensical argument (null
, ''
, etc). Fix the issue at the lowest level possible rather than at a higher level. Then the result of the overall calculation has a good chance of making sense, and you're not substituting some magic number (0 or 1 or whatever) for the result of the entire calculation. (The trick of (parseInt(foo.value) || 0) works only for sums, not products - for products you want the default value to be 1 rather than 0, but not if the specified value really is 0.)
Perhaps for ease of coding you want a function to retrieve a value from the user, clean it up, and provide a default value if necessary, like this:
function getFoobarFromUser(elementid) {
var foobar = parseFloat(document.getElementById(elementid).innerHTML)
if (isNaN(foobar)) foobar = 3.21; // default value
return(foobar.toFixed(2));
}
Methods that use isNaN do not work if you're trying to use parseInt, for example:
parseInt("abc"); // NaN
parseInt(""); // NaN
parseInt("14px"); // 14
But in the second case isNaN produces false (i.e. the null string is a number)
n="abc"; isNaN(n) ? 0 : parseInt(n); // 0
n=""; isNaN(n) ? 0: parseInt(n); // NaN
n="14px"; isNaN(n) ? 0 : parseInt(n); // 14
In summary, the null string is considered a valid number by isNaN but not by parseInt. Verified with Safari, Firefox and Chrome on OSX Mojave.
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