by haswell · 4y ago · 0 comments
let isEven = theNumber % 2 == 0;
There are reasons to dislike JavaScript, but this isn’t it. The native solution is about as standard as it gets.Because I firmly believe that crap like this happens because the language itself is very, very dumb.
However, some variation on n%2==0 is idiomatic in a large number of languages, both modern and old [0].
This includes Lua, Java, Python, Scala, Perl, PHP, Swift, and many others.
It is true that there are numerous languages with built in convenience methods in their standard libraries, but that does not by itself mean that n%2==0 is problematic and certainly this idiom is deeply entrenched.
There is nothing preventing a developer using those languages from wrapping this in a function, and indeed this is probably a good idea if it’s something you find yourself using repeatedly throughout your code base, just like any other often-repeated code snippets.
It’s like doing a for(i=0; i<items.length:i++) { e=items[i] } to iterate over each element instead of something like foreach, or a lambda.
How is that for loop not expressing what it means? for is used to iterate over something. There are legitimate reasons to choose for even when forEach is available.
Does this not express what I mean?
if (amount > balance)
return “insufficient_funds”;
Chances are, I’ll put this in a method anyway, and that’s what a language enables me to do - to create meaning that is contextual to my program.Abstraction can help simplify complex problems, and that’s what it is good at. But when literally everything is abstracted away, it becomes harder to reason about what the program is doing without also learning about what the particular abstraction does (e.g. implicitly handling negative numbers, etc).
A well implemented standard library can be a joy to use, and some people choose languages for this reason. Some languages very intentionally provide a very lightweight standard library, and that’s just fine. All of this shouldn’t absolve the developer from understanding some of the very basic constructs of the language they choose - a lack of which will lead to bugs and vulnerabilities.
If I choose JavaScript (or it’s chosen for me), it behooves me to understand the basics vs. farming this out to some node package that just made my app harder to reason about and vulnerable to supply chain attacks for essentially no value.