3 ms·
Correctly checking if a variable is odd is not quite as simple in a dynamic, type-coercing library like ECMAScript as you might think. You have to consider thin
by stupidcar 9y ago
Correctly checking if a variable is odd is not quite as simple in a dynamic, type-coercing library like ECMAScript as you might think. You have to consider things like: is the variable null or undefined? Does it have the Number type? Is the number an integer? Is the integer odd? In a statically typed language, the compiler would guarantee many of these things for you, but in ES you need to do it yourself.
It's not rocket science, but it's tricky enough that you could perhaps make a mistake or overlook something. To be safe in these situations, when writing a small amount of "nearly trivial" code, programmers have generally resorted to a package manager called "Google / Stack Overflow".
This package manager works as follows: You Google for "safely check if odd in JavaScript", open the top Stack Overflow link, then copy and paste the answer (usually a single function) into your codebase. Then you add a comment saying "taken from https://stackoverflow.com..." https://stackoverflow.com...". Whenever you have another piece of "nearly trivial" code to write, you install it the same way.
ES developers thought that this workflow could be optimised a bit. To that end, they invented a package manager called "npm". Unlike the Google / Stack Overflow manager above, this lets you install functions like "is-odd" without having to manually copy and paste them from your browser. It also keeps track of where they came from, who authored them, and even lets them be updated, if necessary.
- goatlover 9y agoIn that case, sounds like is_odd/even should be part of the language, given how widely used and basic it is. Useful methods get added to strings, arrays and objects each ES release.
- charliesome 9y ago> You have to consider things like: is the variable null or undefined? Does it have the Number type? Is the number an integer? This is a non-problem. If you really have to consider all these edge cases before testing if a number is odd or even that's a sign you need to seriously rethink your domain model, not reach for a library that has already thought about these edge cases for you. Well written dynamic code should be mostly statically typed.
- sedeki 9y agoIf every one of your functions are type asserting at run-time, I think you should just switch to a statically typed language.