4 ms·
You'll love the output of ['1', '7', '11'].map(parseInt)
by dividuum 6y ago
You'll love the output of ['1', '7', '11'].map(parseInt)
- jannes 6y agoNumber() only takes a single parameter. The correct version is: ['1', '7', '11'].map(Number)
- dahfizz 6y agoIf only the language did anything at all to help you realize the wrong version is wrong and that this is somehow different.
- davidmurdoch 6y agoCareful with that: https://jakearchibald.com/2021/function-callback-risks/ https://jakearchibald.com/2021/function-callback-risks/ Using `Number` is probably safe because it'd break much of the web of it were changed. Also note that it is not equivalent to parseInt, as Number and parseInt apply different parsing rules.
- dividuum 6y agoThanks for linking that post. I meant to include it in my comment but wasn't able to find it again.
- pmontra 6y agoOne would assume it to be equivalent to (written in the most old style possible way so everybody can understand it) ['1', '7', '11'].map(function(n) {return parseInt(n);}) but no, map has got an extra argument, the index of the array function traceParseInt(n, i) { console.log(i); return parseInt(n, i); } ['1', '7', '11'].map(traceParseInt) 0 1 2 [ 1, NaN, 3 ] Nice way to wait for an integration test to complete. Thanks.
- erichocean 6y agoAnd parseInt() also take an extra argument, the "base" of the number—hence the weird results. (Which also means that a static type checker would not have caught this "bug".)
- nobleach 6y agoI've always found this example so frustrating. JavaScript isn't curried. Plenty of languages are not. `parseInt` is overloaded/variadic. What we know is if one does not read the documentation for `parseInt`, they might get unexpected results... but who's fault is that? I don't see this a a "hidden gotcha". Yes, if you came from say.... Pascal, and you were used to `StrToInt` taking one arg, and you refused to check into it, you'd get odd results. But who among us, when learning a new language don't look up things like, "how to convert a string to an integer in <insert name of new language>"? That search will most likely land you at some docs that explain that second arg.