Search code examples
javascriptparseint

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?


Solution

  • 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.