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
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.
What you are expecting is this :
isNaN(parseInt("-0x123")); // returns -291
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