2

Can someone explains me why

["23", "45", "67"].map(parseInt); returns [ 23, NaN, NaN ]

but

["23", "45", "67"].map((e) => parseInt(e)); returns [ 23, 45, 67 ]

?

Grégory
  • 338
  • 2
  • 10

1 Answers1

3

["23", "45", "67"].map(parseInt) is basically:

["23", "45", "67"].map((e, i) => parseInt(e, i))

So, it is internally..

  • For "23" i is 0. Thus parseInt('23', 0) // 23
  • For "45" i is 1. Thus parseInt('45', 1) // NaN
  • For "67" i is 2. Thus it parseInt('67', 2) // NaN

In this ["23", "45", "67"].map((e) => parseInt(e));, default radix is 10. So it gives you back [23, 45, 67].

Read the MDN Guide to understand why in this case default radix is selected as 10.

Arup Rakshit
  • 116,827
  • 30
  • 260
  • 317