Is there a best way to prevent NaN? I have number input field that whenever I clear the field, I get NaN.
_amount: function(e) {
var value = parseInt(e.target.value);
var newValue = (value === NaN ? 0 : value); // Thought this could work
},
<input type="number" value={this.state.amount} onChange={this_amount} />
Now in my render I have 400 - this.state.amount. The things is, when I clear the input field, amount state is null. How to prevent this? Is it possible that when I clear the field I get zero? Say I type in 3 then clear the field, NaN pops up.
Thanks
NaNis never equals to anything includingNaNitself hence rely onNumber.isNaN(value)method.
_amount: function(e) {
var value = parseInt(e.target.value);
var newValue = (isNaN(value) ? 0 : value);
//OR sorthand as `NaN` is falsey
var value = parseInt(e.target.value) || 0;
}
isNaN functionUnlike all other possible values in JavaScript, it is not possible to rely on the equality operators (
==and===) to determine whether a value isNaNor not, because bothNaN == NaNandNaN === NaNevaluate to false. Hence, the necessity of anisNaNfunction.[Ref]
The shortest way I found was
var number = (yourVariable || 0)
Because NaN is a falsey value, this will return 0 whenever yourVariable is NaN.
A way to check, if a number is NaN or not is to use the isNaN function.
isNaN(yourVariable); // Returns true is yourVariable is NaN
Side note:
The above method can be used for multiple problems too. For example: getting a value from an array (wich may not exist) and getting a value from a 2d array.
Getting value from array:
yourArray[i] || 0
Where i is the id you want to access
Getting value from a 2D array:
(yourArray[i] || [])[j] || 0
Where i and j are the position of the element in the array
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