0

When running

["6", "1", "0", "3", "3"].map(parseInt)

in the JavaScript console in my browser, I get the output

[6, NaN, 0, NaN, 3]

! But I was expecting

[6, 1, 0, 3, 3]

.

It seems that this might have to do with the fact that parseInt can accept two arguments instead of one. I was under the impression that map merely called the given function on each element of the array separately. Can somebody clarify how map works and why it leads to this odd behavior?

mareoraft
  • 3,474
  • 4
  • 26
  • 62
  • `["6", "1", "0", "3", "3"].map(v => parseInt(v))` seems to work. not sure why it doesn't work with just the function. – Davin Tryon Feb 08 '19 at 16:44
  • Try this: ["6", "1", "0", "3", "3"].map(v => parseInt(v, 10)); – pid Feb 08 '19 at 16:49
  • This is indeed a duplicate. I would not have created this question if I had found the other one during my initial search. – mareoraft Feb 08 '19 at 23:06

2 Answers2

2

According to the documentation, parseInt accepts two parameters: string integer and base. At the same time, map passes two arguments: value and index.

So, basically your call is equivalent to this:

["6", "1", "0", "3", "3"].map((value, index) => parseInt(value, index))

which results into NaN when it is not possible to parse it with given parameters.

Particularly:

  • parseInt("6", 0) is working, because it seem to use default base (10)
  • parseInt("1", 1) is failing, because 1 is invalid base
  • parseInt("0", 2) is working, it is a binary representation of decimal 0
  • parseInt("3", 3) is failing, because there can be no "3" in base 3
  • parseInt("3", 4) is working, it is a 4-base representation of decimal 3
Yeldar Kurmangaliyev
  • 33,467
  • 12
  • 59
  • 101
  • 1
    This is a great explanation. It only lacks a link to the [map documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map) where you can verify that `map` passes in 3 arguments (or 2 if it can't (or 1 if it can't)) to the function. – mareoraft Feb 08 '19 at 23:03
1

The reason is because parseInt is parseInt(string, radix);

And when map runs it returns the arguments (value, index, array)

so it is being run as

parseInt("6", 0);
parseInt("1", 1);
parseInt("0", 2);
parseInt("3", 3);
parseInt("3", 4);
epascarello
  • 204,599
  • 20
  • 195
  • 236