Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Javascript isNaN function declare string negative hex values to be NaN?

Tags:

javascript

Given the following example:

isNaN("-0x123");    // returns true , meaning is not a number <- Why?
isNaN(-0x123);      // returns false, meaning is a number
isNaN("0x123");     // returns false, meaning is a number
parseInt("-0x123"); // returns -291

My question: why does isNaN declares negative hex strings as NaN when other similar inputs yield more reasonable outputs?

Thanks

like image 915
nivla12345 Avatar asked Jan 07 '23 23:01

nivla12345


2 Answers

The function isNaN() tells you whether or not a value may be coerced to a number, it says nothing about whether there exists a function that will convert the value to a number.

You will see the same behaviour if you attempt to coerce the strings to numbers:

> +"-0x123"
NaN
> +(-0x123)
-291
> +"0x123"
291

The first case you have a string that does not match Javascript's rules for a number as that doesn't allow for a leading - on a hex literal, the second case you have an expression that evaluates to a number (so 0x123 negated), the third case you have a string that does match the grammar for a number.

See http://www.ecma-international.org/ecma-262/5.1/#sec-9.3 for the exact description, but in short a string numeric literal may be an unsigned decimal literal, + or - followed by an unsigned decimal literal, or it may be a hex integer literal (and in all these cases leading and trailing whitespace is ignored). There is no option for a sign on a hex literal.

like image 176
Duncan Avatar answered Jan 09 '23 18:01

Duncan


What you are expecting is this :

isNaN(parseInt("-0x123")); // returns -291
like image 44
Cijo V J Avatar answered Jan 09 '23 20:01

Cijo V J