by vortico · 3y ago · 0 comments
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.
But you can't!!!
> Every language that supports default and variable arguments does this.
Python:
map(float, ["1", "2", "3"])
C:No equivalent syntax.
C++
std::vector<std::string> a = {"1", "2", "3"};
std::vector<int> b;
std::transform(a.begin(), a.end(), std::back_inserter(b), std::stod); # compile error
You can say "well feature X exists elsewhere" or "library function Y exists elsewhere", but only JS makes the collective design choices that cause this phenomenon.Good, bad? IDK, that's subjective. But unique? Certainly.
> help(int)
class int(object)
| int([x]) -> integer
| int(x, base=10) -> integer
> list(map(int, ["1", "2", "3"]))
[1, 2, 3]
Even if you define a function that takes two parameters, it complains about not having a second one: >>> def to_int(a, b):
... return int(a, base=b)
...
>>> list(map(to_int, ["1", "2", "3"]))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: to_int() missing 1 required positional argument: 'b'