-1

I ran into an issue regarding array mapping functions in JS and cannot explain why this is happening, nor do I find any helpful search results with an explanation. Sorry if this was posted already somewhere.

Could anyone explain why the results differ?

const [ i, j ] = "1x2".split('x').map((value) => parseInt(value));
console.log(i);
console.log(j);

const [ i, j ] = "1x2".split('x').map(parseInt);
console.log(i);
console.log(j);

cheers

raQai
  • 68
  • 1
  • 7

1 Answers1

2

parseInt receives as second argument the radix:

radix Optional

An integer between 2 and 36 that represents the radix (the base in mathematical numeral systems) of the string. Be careful—this does not default to 10! If the radix value is not of the Number type it will be coerced to a Number.

So, when you do:

const [ i, j ] = "1x2".split('x').map(parseInt);

it is the same like:

const [ i, j ] = "1x2".split('x').map((value, index) => parseInt(value, index));

(the map callback is called with currentValue, currentIndex and arrayReference)


Hence, parseInt("2", 1) is NaN because 1 is not a valid radix value.

Ionică Bizău
  • 109,027
  • 88
  • 289
  • 474
  • 1
    The last point you could explain is why `parseInt("1", 0)` returns 1. –  Jul 07 '21 at 12:15