Why using parseInt on Error returns 14?

Consider the following:

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

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

This behavior seems to be unique to Error / Error instances. Can someone give an idea?

+4
source share
1 answer

Basically, this is because:

  • new Error().toString()gives "Error"and
  • parseInt("Error", 16)gives 14(because there 0xEis 14, and the parser stops at r).

On the other hand, it new Array()does not cause the same behavior, because the toString()array object method returns the contents of the array, separated by commas, and not the class name. Consequently, new Array().toString()gives an empty string, and parseInt()subsequently gives NaN.

+11
source

Source: https://habr.com/ru/post/1627818/


All Articles