Find the bug · #21 · Types and comparisons Medium JavaScript
Imported ids turn into NaN
An import turns a column of order ids into numbers, and only the first one survives.
On this page
The report
An import reads a column of order ids from a CSV file and turns them into numbers. Only the first id comes through: the rest become NaN, or the wrong id altogether.
The code
Read it first: what should it do? Then click the line where you think the bug is.
// Turns a CSV column of ids into numbers.
function parseIds(column) {
return column.split(',').map(parseInt);
}Read it, then pick a line.
map calls your function with more than one argument. What is parseInt’s second parameter?
What it prints
Running it on a small example prints the output on the left. It should print the output on the right.
console.log(JSON.stringify(parseIds('7,8,9,10')));It prints
[7,null,null,3]
It should print
[7,8,9,10]
Show the answer: the bug, the fix, and how you’d find it
The bug (line 3)
Line 3 passes parseInt straight to map. But map calls it with two arguments, the value and its index, and parseInt’s second argument is the radix, the number base. So “8” is read in base 1 (NaN), “9” in base 2 (NaN) and “10” in base 3 (which is 3). Use s => parseInt(s, 10), or Number.
The fix
1// Turns a CSV column of ids into numbers.2function parseIds(column) {3 return column.split(',').map(parseInt);3 return column.split(',').map((s) => parseInt(s, 10));4}How you’d find it
- Reproduce:
parseIds("7,8,9,10")gives[7, NaN, NaN, 3](NaNprints asnullin JSON). - The first value is right and the rest go wrong in a pattern, so something depends on the position. That’s the index
mappasses as a second argument. - Check
parseInt’s signature:parseInt(string, radix). The index is being used as the base.
The test that catches it
It fails on the code above and passes once it’s fixed. Keep it, so the bug can’t come back.
assert.deepEqual(parseIds('7,8,9,10'), [7, 8, 9, 10]);
assert.deepEqual(parseIds('42'), [42]);Where else this bites
["1", "2", "3"].map(parseInt)giving[1, NaN, NaN]is a classic interview question.- Any callback with optional parameters, passed straight to
maporforEach.