2

I found some strange behavior in the javascript parse int function.

Check the following code:

console.log([..."111"].map(Number.parseInt))
console.log([..."111"].map(x => Number.parseInt(x)))

When you run the first line, you get: [1, Nan, 1]

When you run the second line, you get: [1, 1, 1]

Can someone explain this strange behavior?

pedroth
  • 563
  • 1
  • 6
  • 14

2 Answers2

2

The parseInt() function is defined with two parameters: the string to parse, and a number indicating the numeric base to assume for the string representation. On the second iteration, the .map() call is effectively calling

Number.parseInt("1", 1)

and base 1 does not make sense. (Base 0 does not make sense either, but it ignores that.)

Recall that the .map() function passes 3 parameters to its callback function: an element from the array, an index, and the array itself.

Pointy
  • 389,373
  • 58
  • 564
  • 602
1

Number.parseInt accepts 2 arguments if the second argument (called radix in MDN docs) is smaller than 2 or greater than 36, NaN is returned.

Igor Bykov
  • 2,011
  • 3
  • 10
  • 16