CodePark/ questions / Arrays & objects
START PRACTICINGPRACTICE
Frontend question · JavaScript › Arrays & objects

What does this log?

console.log(["1", "2", "3"].map(parseInt));
[ 1, NaN, NaN ]

The answer is [ 1, NaN, NaN ]. map calls the callback with three arguments: (element, index, array). parseInt reads its second argument as the radix (the number base).
•
parseInt('1', 0) treats radix 0 as the default, 10, so it gives 1.
•
parseInt('2', 1) has an invalid radix, so it gives NaN.
•
parseInt('3', 2) fails because 3 is not a binary digit, so it gives NaN.

The tempting option "[ 1, 2, 3 ]" is wrong because it assumes
map passes only the element. Use .map(Number) or .map(s => parseInt(s, 10)) instead.