Why does ['1', '2', '3'].map(parseInt) not give [1, 2, 3]?
map passes three arguments to the callback: item, index and array. parseInt uses the second as the radix, so it runs parseInt('2', 1) and parseInt('3', 2), both NaN. Use map(Number) or map(s => parseInt(s, 10)).
Explain it simply
map calls your function with (item, index, array). Normally you ignore the extras. But parseInt(string, radix) takes two parameters, so the index sneaks in as the radix (the number base).
The calls are:
parseInt("1", 0): radix 0 means "use 10", so1.parseInt("2", 1): radix 1 is not valid, soNaN.parseInt("3", 2): the digit 3 does not exist in binary, soNaN.
The fix is to control the arguments yourself.
Example
console.log(["1", "2", "3"].map(parseInt).join()); // Output: 1,NaN,NaN
console.log(["10", "10", "10"].map(parseInt).join()); // Output: 10,NaN,2
console.log(["1", "2", "3"].map(Number).join()); // Output: 1,2,3
console.log(["1", "2", "3"].map((s) => parseInt(s, 10)).join()); // Output: 1,2,3Here parseInt("10", 2) reads 10 as binary, which is 2.
What to say in the interview
"map passes item, index and array. parseInt treats the index as its radix, so after the first element the results are NaN. I either pass an arrow function that fixes the radix at 10 or use Number as the callback."
Common mistakes
- Passing any function with optional second parameters straight to map without checking its signature.