-1

Why is it that, when I use parseInt explicitly with the first argument, everything works as I expect, but with I straight up supply the parseInt function to map, it becomes like you can see in the picture?

I've read up a little bit on the second radix-argument of parseInt, and I suppose it has something to do with that. But I still don't understand what JS internally supplies to the parseInt function as the second argument when I don't explicitly do it myself. Does anyone know?

parseInt

Mureinik
  • 297,002
  • 52
  • 306
  • 350
Dawid Dahl
  • 129
  • 1
  • 8
  • MDN addresses this exact scenario [here](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map#Tricky_use_case) – Nick Parsons Dec 30 '19 at 14:50

2 Answers2

0

Because .map calls function with two parameters, the second being an index of an element, so your parseInt call in the second case gets strange radix.

Example:

> function f(x, y) {
... console.log(x, y);
... }
undefined
> [1, 2, 3, 4].map(x => x.toString()).map(f)
1 0
2 1
3 2
4 3

When you call .map(parseInt), then parseInt gets both. When you call .map(x => parseInt(x)) the second gets ignored, and parseInt is called with one parameter only and default radix.

(Actually, there's the third argument as well; read Array.map documentation.)

avysk
  • 1,973
  • 12
  • 18
0

It's because all of the array methods pass 3 arguments to your callbacks, the first argument is the array element at each index, the second argument is the index, and the last one is the array itself. When you pass a reference to a callback directly like in your second example, Javascript implicitly passes all 3 arguments into your callback, so the indices being passed in your parseInt are used as the radix, and when parseInt is given an invalid radix, it just returns NaN. While in your first example, you explicitly pass only the array elements yourself, and you are leaving out the radix argument for parseInt, so base 10 is assumed

Trash Can
  • 6,608
  • 5
  • 24
  • 38
  • Thank you so much for your answer! Now I know more clearly what's going on when you use a function like that in map for example. Yay! – Dawid Dahl Dec 30 '19 at 14:52
  • I realize now with the great answers in this thread, that I can do ["1","2","3"].map(Number) instead and it will work as I originally expected, because Number only has one parameter! – Dawid Dahl Dec 30 '19 at 15:46