Let's run this javascript code:
var value = parseInt("");
console.log(value != Number.NaN? value : null);
Why does this code outputs Nan
in the console instead of null
?
How can I change my code to actually get a null
object ?
I try to wrap my code in a function like this:
function parseIntOrDefault(value, def){
var candidate = parseInt(value);
if(candidate != Number.NaN) return candidate; else return def;
}
console.log(parseIntOrDefault('', null));
But this behaves the same.
Here is a jsFiddle that illustrate my issue: http://jsfiddle.net/stevebeauge/BRP94/
The concept of null null is a primitive value that represents the intentional absence of any object value. If you see null (either assigned to a variable or returned by a function), then at that place should have been an object, but for some reason, an object wasn't created.
Related Definitions null return means a return which indicates that no transaction was made by the registered person during the tax period and no amount of tax is to be paid or refunded. Sample 1.
Several alternatives for returning null values include using null object reference types, a null object pattern, and a result type as the return type. Therefore, the recommendation is to return an empty value instead of a null to keep the code clean and error-free.
The rationale behind not returning null is that you do not have to check for it and hence your code does not need to follow a different path based on the return value. You might want to check out the Null Object Pattern which provides more information on this.
You should use
isNaN(value);
to check for NaN
Because:
console.log(NaN === NaN); // false!
NaN
is not equal to itself.
This may seem weird but it makes sense if you think about the nature of NaN
.
Let's say you have this code:
var a, b, c;
// a = 0;oops a is still undefined so we'll get NaN if we do an operation with it
b = 5;
c = 6
if (a + b === a + c) {
console.log("math error?");
}
You don't want to come to the seeming conclusion that 5 === 6.
if(isNaN(candidate))return null; else return candidate;
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