0
['1', '4', '9', '16'].map(parseInt)

gives

[1, NaN, NaN, 1]

But

['1', '4', '9', '16'].map(x => parseInt(x))

gives

[1, 4, 9, 16]

Why?

takendarkk
  • 3,347
  • 8
  • 25
  • 37
Mark Farmiloe
  • 396
  • 3
  • 8
  • Because `parseInt` accept TWO arguments but the second one is optional and array.map will pass THREE arguments to `parseInt`. So basically you have incompatible understanding of arguments. `parseInt` expects `parseInt(string, base)` eg if you want to parse a hex number like `3a` or `ff` you can do `parseInt("ff", 16)`. **BUT** `array.map()` will pass you `(item, index, array) => {}` so the first item you will get `parseInt('1', 0)` which I assume will be interpreted as base-10 number because base-0 makes no sense, then `parseInt('4', 1)` which is a base-1 number. Base-1 is weird but exists.. – slebetman Aug 05 '21 at 15:18
  • ... then `parseInt('9', 2)` which is a binary number like `1011001` or `111001` so the digit '9' is not a valid binary digit. Then finally `parseInt('16', 3)` which is a base-3 number. The digit '6' is not a valid base-3 number. Base-3 numbers are like '10012210102'. So in this case `parseInt` treats '6' as a non-number character. It works the same as `parseInt('5hello')` which returns '5'. In this case it treats it like `parseInt('1K',3)` so it returns 1 – slebetman Aug 05 '21 at 15:23
  • See the answers to similar question. Put simply the map method will pass 3 arguments to the function it is passed by default. only by explicitly using the first argument can you stop the other two arguments being passed to parseInt and confusing it. – Mark Farmiloe Aug 05 '21 at 15:31
  • See https://stackoverflow.com/questions/262427/why-does-parseint-yield-nan-with-arraymap as this gives a good answer. – Mark Farmiloe Aug 06 '21 at 15:57

0 Answers0