Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 248
savax0 Avatar asked Dec 18 '22 19:12

savax0


1 Answers

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.

like image 192
Frédéric Hamidi Avatar answered Jan 05 '23 03:01

Frédéric Hamidi