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…

--

--

Eric Tong
DailyJS

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