BugHunt

['1', '2', '3'].map(parseInt) returns [1, NaN, NaN]

map() passes each item's index as a second argument, and parseInt treats its second argument as the radix (number base).

JavaScriptType errors

What it means

map calls parseInt("1", 0), parseInt("2", 1), parseInt("3", 2). Radix 0 means "guess" (10), radix 1 is invalid (NaN), and "3" is not a binary digit (NaN). Any function with an optional second parameter can misbehave when passed straight to map.

Common causes

1. Passing parseInt directly to map

The index becomes the base.

Breaks

["10", "10", "10"].map(parseInt)   // [10, NaN, 2]

Works

["10", "10", "10"].map((s) => parseInt(s, 10))   // [10, 10, 10]

2. Wanting decimals

parseInt drops the fraction.

Breaks

["1.5", "2.5"].map((s) => parseInt(s, 10))   // [1, 2]

Works

["1.5", "2.5"].map(Number)   // [1.5, 2.5]

How to find it in your own code

Wrap the function so it receives only the value: arr.map((s) => parseInt(s, 10)), or use arr.map(Number), which takes a single argument.

Try it: fix this bug

medium

parseAll(["10", "10", "10"]) returns [10, NaN, 2].

function parseAll(strings) {
    return strings.map(parseInt);
}
Open with hintsRuns in your browser. No account needed.

Still not sure why yours breaks?

Paste it into the visualizer and watch it run line by line, with every variable at every step. Free, and it runs in your browser.

Other common errors