0

If I map through an array using parseInt it returns unexpected and incorrect results:

console.log(["1234-04-23", "1234", "04", "23"].map(parseInt))
// => [1234, NaN, 0, 2]

but redundantly adding an arrow function wrapper works as expected

console.log(["1234-04-23", "1234", "04", "23"].map(e => parseInt(e)))
// => [1234, 1234, 4, 23]

These two statements should behave identically, so why does the first one break?

Kos
  • 4,890
  • 9
  • 38
  • 42
JD.
  • 2,361
  • 6
  • 25
  • 38
  • 2
    Because `parseInt` takes more than just one argument. [Look it up.](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt). Also, `Array.map` passes more than one argument to the callback. [Look that up too](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map). – Niet the Dark Absol Jan 27 '18 at 19:28

1 Answers1

1

Because map adds a second and third parameters: the index and the array itself. See:

["1234-04-23", "1234", "04", "23"].map(console.log);
// => 1234-04-23 0 ["1234-04-23", "1234", "04", "23"]
// => 1234 1 ["1234-04-23", "1234", "04", "23"]
// => 04 2 ["1234-04-23", "1234", "04", "23"]
// => 23 3 ["1234-04-23", "1234", "04", "23"]

As you can see in the specification, parseInt also accepts a second parameter as base, so you are actually doing this:

console.log(["1234-04-23", "1234", "04", "23"].map((e, e2) => parseInt(e, e2)));
// => [1234, NaN, 0, 2]

The NaN is because:

parseInt stops at the first invalid character and returns whatever it has at that point. If there are no valid characters to parse, it returns NaN

Source: https://stackoverflow.com/a/39147168/1525495

Jorge Fuentes González
  • 11,568
  • 4
  • 44
  • 64