1

Hi JavaScript masters !

console.log([ '5', '9', '7' ].map(parseInt)) tells me [5, NaN, NaN]

console.log([ '5', '9', '7' ].map(function(element){
    return parseInt(element)
}))

tells me [5, 9, 7]

But why ? ^^'

3 Answers3

2

This happens because, as it is described here:

parseInt is often used with one argument, but takes two. The first is an expression and the second is the radix to the callback function, Array.prototype.map passes 3 arguments:

  • the element
  • the index
  • the array

The third argument is ignored by parseInt, but not the second one, hence the possible confusion.

Community
  • 1
  • 1
Christos
  • 53,228
  • 8
  • 76
  • 108
0

map calls the function you give it with 3 parameters: the value, the index of it in the array, and the array itself. Your second approach safely ignores these, but your first one causes the second parameter to be interpreted as the base of the number, which isn't what you wanted.

0

Best explained here: https://stackoverflow.com/a/262511/6935763

No use of copying pasting here the whole answer

Abhay Maurya
  • 11,819
  • 8
  • 46
  • 64
  • 1
    Posting a link isn't very useful either. Just cast a duplicate vote. – georg Oct 08 '19 at 12:31
  • um...i did? You can see my name there who marked it duplicated! I just posted as an answer for anyone who scrolls down looking for answer here anyway – Abhay Maurya Oct 08 '19 at 12:38