Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why isn't this returning null?

Tags:

javascript

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/

like image 737
Steve B Avatar asked Jun 28 '13 15:06

Steve B


People also ask

Why is my object returning null?

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.

What does it mean return null?

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.

What to do instead of returning null?

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.

Why you should not return null?

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.


2 Answers

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.

like image 155
Halcyon Avatar answered Oct 09 '22 02:10

Halcyon


if(isNaN(candidate))return null; else return candidate;    
like image 44
JJ123456 Avatar answered Oct 09 '22 01:10

JJ123456