Some strange behavior in Js Number.parseInt function, can someone explain it?

Viewed 55

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?

2 Answers

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.

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.

Related