Fun with JavaScript: the mystery of the failing parse
See if you can figure that one out in less than ten seconds, in which case kudos to you… What does this code return?
['1', '2'].map(parseInt)
If you answered
[1, 2]
I'm sorry to say that you're as wrong as I was when I wrote this bug.
Now if you answered
[1, NaN]
well, congratulations! So what’s going on here?
The `Array.prototype.map` method calls the passed-in function with three parameters: the current array item, its index, and the array. The `parseInt` function can take two parameters: the string to parse, and the radix. If you forget about that second parameter, you may think that the additional parameters that `map` passes in would get ignored. Not so in this case. `parseInt` is called twice. The first time with the parameters ('1', 0) (the third one will be ignored), the second time with ('2', 1). The radix is supposed to be between 2 and 36 (why 36? I don’t know). Radix zero gets ignored and works like the default, while 1 yields `NaN`.
The moral of the story is, don’t try to be too clever. The code above can be more explicitly, and more correctly written like so:
['1', '2'].map(function(n) {return parseInt(n, 10);})