Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save 3imed-jaberi/6b6d5cc52531b60b2a31e8dd566957bf to your computer and use it in GitHub Desktop.

Select an option

Save 3imed-jaberi/6b6d5cc52531b60b2a31e8dd566957bf to your computer and use it in GitHub Desktop.
Why ['1', '7', '11'].map(parseInt) returns [1, NaN, 3] in Javascript.
/**
* ['1', '7', '11'].map(parseInt) doesn’t work as intended because map passes
* three arguments into parseInt() on each iteration. The second argument
* index is passed into parseInt as a radix parameter. So, each string in the array
* is parsed using a different radix. '7' is parsed as radix 1, which is NaN,
* '11' is parsed as radix 2, which is 3. '1' is parsed as the default radix 10,
* because its index 0 is falsy.
*
* And so, the following code will work as intended;
*/
['1', '7', '11'].map(numberStr => parseInt(numberStr))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment