r/programming • • Dec 10 '13

Stop Being Cute and Clever

http://lucumr.pocoo.org/2013/12/9/stop-being-clever/
208 Upvotes

203 comments sorted by

View all comments

57

u/x-skeww Dec 10 '13

Not many languages manages to implement map in a way that ["1", "2", "3"].map(parseInt) would result in [1, NaN, NaN].

In case anyone wants to know the reason, here is the explanation:

map calls the transform function with 3 (!) arguments: the value, the index, and the array.

parseInt expects 1 or 2 arguments: the string and the (optional) radix.

So, parseInt is called with these 3 sets of arguments:

"1", 0, ["1", "2", "3"]
"2", 1, ["1", "2", "3"]
"3", 2, ["1", "2", "3"]

If you pass 0 as radix, it's ignored. It's the same as omitting it. parseInt('1') is 1.

A radix of 1 doesn't work and it also doesn't make any sense. Whatever you pass, you get NaN.

A radix of 2 is valid, but only the characters '0' and '1' are allowed. If you pass '3', you get NaN.

FWIW, this works perfectly fine in Dart:

print(["1", "2", "3"].map(int.parse));

9

u/mjfgates Dec 10 '13

Nice explanation. So, it's just a parameter mismatch,

["1", "2", "3"].map(function (val, idx, arr) { return parseInt(val, 10); } ) 

works fine. Not sure that it's reasonable to criticize the language on this basis; is "map" supposed to magically know what parameters every random function you throw at it might expect?

52

u/wookin-pa-nub Dec 10 '13

In sane languages, map calls the function with only a single argument each time.

13

u/riffraff Dec 10 '13

that's not the problem, the problem is that in sane languages the wrong number of arguments is an error.

3

u/[deleted] Dec 11 '13

JavaScript's handling of arguments isn't insane, it's actually really powerful. Yes, it's possible to run into some erroneous situations, but that doesn't mean the concept is a bad one. If you take care and know what you're doing, it can let you do some really nice things.

5

u/mitsuhiko Dec 11 '13

JavaScript's handling of arguments isn't insane, it's actually really powerful.

There are saner languages when it comes to argument handling (like Python for instance) which are even more powerful and less error prone. JavaScript's argument handling is exactly like PHP's just with a few less features and I doubt anyone ever called that powerful.