Search code examples
javascriptarraysecmascript-6parseint

Why does parseInt returns NaN when used with Array.map?


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?


Solution

  • 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