Why ['1', '7', '11'].map(parseInt) returns [1, NaN, 3] in Javascript

Eric Tong
DailyJS
Published in
5 min readJun 12, 2019

--

???

Javascript is weird. Don’t believe me? Try converting an array of strings into integers using map and parseInt. Fire up your console (F12 on Chrome), paste in the following, and press enter (or run the pen below).

['1', '7', '11'].map(parseInt);

Instead of giving us an array of integers [1, 7, 11], we end up with [1, NaN, 3]. What? To find out what on earth is going on, we’ll first have to talk about some Javascript concepts. If you’d like a TLDR, I’ve included a quick summary at the end of this story.

Truthiness & Falsiness

Here’s a simple if-else statement in Javascript:

if (true) {
// this always runs
} else {
// this never runs
}

In this case, the condition of the if-else statement is true, so the if-block is always executed and the else-block is ignored. This is a trivial example because true is a boolean. What if we put a non-boolean as the condition?

if ("hello world") {
// will this run?
console.log("Condition is truthy");
} else {
// or this?
console.log("Condition is falsy");
}

Try running this code in your developer’s console (F12 on Chrome). You should find that the if-block runs. This is because the string object "hello world" is truthy.

Every Javascript object is either truthy or falsy. When placed in a boolean context, such as an if-else statement, objects are treated as true or false based on their truthiness. So which objects are truthy and which are falsy? Here’s a simple rule to follow:

All values are truthy except for: false, 0, "" (empty string), null, undefined, and NaN.

Confusingly, this means that the string "false", the string "0", an empty object {}, and an empty array [] are all truthy. You can double check this by passing an object into the Boolean function (e.g. Boolean("0");).

For our purposes, it is enough to remember that 0 is falsy.

Radix

0 1 2 3 4 5 6 7 8 9 10

When we count from zero to nine, we have different symbols for each of the numbers (0–9). However, once we reach ten, we…

--

--

Eric Tong
DailyJS

I write about the intersection of design and development. Front-end developer at Facebook. eric-tong.com