44 points · by xg15 · 3y ago · 82 comments
> Looking at the specification of parseInt you should notice that it is defined as accepting two arguments. The first argument is the string to be parsed and the second specifics the radix of the number to be parsed. >...the function that is passed as the first argument to map as the callbackfn. The specification says, “the callbackfn is called with three arguments: the value of the element, the index of the element, and the object that is being traversed.”
> Array.prototype.map passes the element's index as the second argument to the callback, and parseInt accepts an optional second argument as the radix (base).
> Using the index as the radix yields a nonsensical result.
In other words, you could do:
parseInt("1");
And you could do: parseInt("1", radix: 16);
But you could never do: parseInt("1", 16);
I swear, this is my #1 wish for programming languages in general. Identifying parameters by position was necessary back when memory was at a premium, but it's always been a disaster for readability and clarity. And we're still all paying the price.Edit: And I'm not talking about named arguments as an option (lots of languages provide this, though not JavaScript). I mean required, where the very concept of argument order (except for first) doesn't even exist.
The article describes the situation in detail, but `parseInt` is called three separate times (its first argument in each call is `"1"`, then `"2"`, then `"3"`, as you'd expect with any array-mapping operation). The weirdness arises because `.map` always passes more than one argument to the callback (and `parseInt` accepts more than one parameter). This happens even when the array has only a single element, it's just that the first call (`parseInt("1", 0, ["1"])`) happens to have the same return value as `parseInt("1")`, so you only notice the weirdness with the later elements.
Passing the index and object for .map() can come in handy sometimes, so I understand the motivation for including it. But with named arguments, they could be passed as something like "_index:" and "_obj:", rather than getting slotted in as an arbitrary [1] and [2], where they can be misinterpreted as other parameters (like "radix").
> (…) it is much more verbose and arguably less elegant.
Article is from 2011 and referencing ES5. With ES6 arrow functions we can make it shorter and more elegant:
["1","2","3"].map(value => parseInt(value))
Because it’s so short, even `n` should suffice and retain clarity: ["1","2","3"].map(n => parseInt(n)) ["1","2","3"].map(parseInt); // returns [1, NaN, NaN]
The gotcha trap is still there, and is just as likely to get through a code review.Arrow functions are graceful and preferred precisely because of this. Passing a naked function reference like that to map is frowned upon where I work, and your PR would not get approval because it is risky for the reasons pointed out in this article.
TL;DR - use modern JavaScript features to make your code more readable and more reliable.
The article is from 2011, and I'm not even sure arrow functions were in the spec at that time. Nowadays the best practice would be: `["1," "2", "3"].map(maybeNum => parseInt(maybeNum))`
[
-1, NaN, // could be better
1, 2, 3, 4, 5, 6, 7, 8, 9, // ok a little bumpy at the start but now we're cookin'
11, 13, 15, 17, 19, 21, 23, 25, 27, 29, // not great not terrible
42 // dang
]
way closer.Pretty sure the Number constructor was made to get you around this. map(Number) does what you would expect.
Map passes 3 parameter to the mapped function, the second one being an index, and parseInt accepts a second optional argument as radix.
be explicit:
["1","2","3"].map(function(x){return parseInt(x,10)})
Javascript isn't the problem here.https://github.com/microsoft/TypeScript/wiki/FAQ#why-are-fun...
By all means, make an extended mapE function that passes all kinds of things like position in the input iterable, a reference to the iterable, a reference to an at-first empty “memo” object that will be discarded at the end of the map call, etc etc.
C++: https://en.cppreference.com/w/cpp/string/basic_string/stol
Java: https://docs.oracle.com/javase/8/docs/api/java/lang/Integer....
C#: https://learn.microsoft.com/en-us/dotnet/api/system.int32.pa...
But they don't have implicit null/undefined for unspecified parameters, and afaik the map's in these languages do not provide additoinal parameters.
Having also written a book about things to look for and abhor in an interview, I consider this question a strong red flag.
I think it would be to say that [...].mapBETTER(argFunk) calls its arg-function with just a single argument. The rest of the useful ("optional") arguments should be passed by binding "this" to the array of them.
If bind() fails because the function was already bound, should throw an error.
But this brings me to my pet-peeve: Why can't I map over Objects (other than Arrays)?
It's part of the core semantics of the language:
function f() {
}
is equivalent to function f(a, b ,c) {
}
because under the hood the latter is simply function f() {
let a = arguments[0]
let b = arguments[1]
let c = arguments[2]
}
Also no one stops you from simply extending the Array.prototype to your heart's content ¯\_(ツ)_/¯JS interfaces are designed with the flexibility and semantics of the language in mind (no surprise there, really) and thus try to cover most use cases. If you don't need the index or the reference to the array in your function, ignore them (e.g. by using map(function(v) { ... })). Passing a function that actually supports more than one argument is by all accounts a layer 8 error and not a fault in the spec of map() IMO.
You could just as well argue that it's bad for parseInt() to accept one or two arguments instead of explicitly requiring both. You'd have to try and convince me why one is perfectly fine while the other is not. You can of course argue that both specs are crap, that'd at least be consistent :)
I'm guessing those quotes were supposed to be " rather than “ and ”.
While each of those flexibilities can be useful, they interact in annoying ways. The fact that map passes three arguments but is often used as if it was passing one, and that parseInt accepts two arguments but is often used as if it accepted one makes it very easy to make this mistake.
This just goes to show how one can use a language without actually understanding its core semantics. Additional arguments aren't "discarded" at all: they're still available to the called function in via `arguments`, they're just not required to be assigned a name in the function signature.
Basically, a Javascript function fn() declaration is equivalent to Python's def fn(*args): declaration and you have the option to assign a name to positional arguments. Any named positional argument that is not provided by the caller simply leaves the argument uninitialized, i.e. undefined.
It's a core concept of the language and I'm always puzzled when non-beginners struggle with this. That's also a very good reason to not use vanilla Javascript at all and skip straight to TypeScript and its brethren instead.
No other language does this.
Every language that supports default and variable arguments does this. This includes Python, C, and C++ and has absolutely zero to do with "loose typing" in this case.
If you post old news, it's customary to say so.
Eg, from dang, the moderator:
https://news.ycombinator.com/item?id=36398290
https://news.ycombinator.com/item?id=36366875
Etc
https://hn.algolia.com/?dateRange=all&page=0&prefix=true&que...
Easy fix too: ["1", "2", "3"].map(i => parseInt(i))
map(some_fun, iterable, *iterables)
`some_fun` would have arity 1 or 1 + len(iterables) and be called only with the values of the passed in iterables, not the enumerated indexes or the original iterables or whatever. To get an equivalent, you'd add in an iterable that corresponded to the indexes explicitly. Same thing with Rust with its `enumerate` which would produce a sequence of pairs `(index, original_item)`. And those aren't atypical when examining `map` in other languages.