Why [‘11’, ‘11’, ‘11’].map(parseInt) returns [11, NaN, 3] in Javascript

Xiangqun Chen
May 1, 2021

Array.prototype.map passes 3 arguments to callback: currentValue, index, array
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map

parseInt takes string and the 2nd optional argument radix.
Valid radix is an integer between 2 and 36.
radix is 10 if 0 is specified and the string doesn’t start with “0x” or “0X”.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt

So the parseInt is called with arguments:

(‘11’, 0, [‘11’, ‘11’, ‘11’]) => 11 // 0 is interpreted as 10
(‘11’, 1, [‘11’, ‘11’, ‘11’]) => NaN // invalid radix
(‘11’, 2, [‘11’, ‘11’, ‘11’]) => 3 // radix is 2

BTW, partialRight of Ramda.js doesn’t help. partialRight just add another argument to the end of the function call.

> const R = require(‘ramda’);
> [‘11’, ‘11’, ‘11’].map(R.partialRight(parseInt, [10]))
[ 11, NaN, 3 ]

--

--