savax0 February 2016

Why does using parseInt on Error return 14?

Consider the following:

parseInt(new Array(), 10); // -> NaN
parseInt(new Array(), 16); // -> NaN

parseInt(new Error(), 10); // -> NaN
parseInt(new Error(), 16); // -> 14

It seems this behavior is unique to Error/instances of Error. Can anyone provide insight?

Answers


Frédéric Hamidi February 2016

Basically, that's because:

  • new Error().toString() yields "Error", and
  • parseInt("Error", 16) yields 14 (because 0xE is 14 and the parser stops at r).

On the other hand, new Array() does not trigger the same behavior because the toString() method of array objects returns the contents of the array, delimited by commas, not the class name. Therefore, new Array().toString() yields the empty string, and parseInt() subsequently yields NaN.

Post Status

Asked in February 2016
Viewed 3,280 times
Voted 14
Answered 1 times

Search




Leave an answer