4 ms·
Most of these scenarios are mitigated by knowing what types of data are coming into your functions. If you're defending against a string being compared to a num
by jessedhillon 12y ago
Most of these scenarios are mitigated by knowing what types of data are coming into your functions. If you're defending against a string being compared to a number, I'd sooner wonder why you don't know whether you have a string or a number in your variable in the first place. What could cause you to attempt to use `[1]`(array containing number 1 as an element) as a boolean? Seems like you should know if a variable contains an array and not true/false, and if you don't then that's a better place to focus your attention.
Happy to hear counterexamples though.
- UweSchmidt 12y agoIf my "number" is in fact a string I'd like to get an error instead of a type conversion that hides this error. This might not necessarily be an ignorant beginner mistake, but may very well be a manifestation of some complicated bug or error on the other end of the program, possibly in a library I haven't studied enough and made assumptions about, or a black-box webservice. I can handle it but don't see why I would go out of my way to defend Javascript in this regard.
- jessedhillon 12y ago> If my "number" is in fact a string I'd like to get an error instead of a type conversion that hides this error. If you expect a number or a string, call parseInt() on your value and then isNaN() on that will tell you whether you have an error condition. Your code will be more understandable if you spend time parsing your inpt and explicitly casting to expected types, rather than papering over differences with ===
- robocat 12y agoWrong jessedhillon, becaue parseInt() is as quirky as == (this is JavaScript, remember!). parseInt('1 are you joking') returns 1. parseInt('077') returns 63 on some older browsers (get off my octal lawn). parseInt('0XALIC ACID') returns 10. parseInt(' -1e5') returns -1. And dealing with Integers in JavaScript is fraught with danger since browser JavaScript only really knows floating point numbers. e.g. parseInt('999999999999999999999999999999999999999999999999999999999999999999999999999999999') returns 1e+81... Smoke that! Edit: It is possible to build some reliable integer routines using logical operators (since they convert to unsigned integers to perform the operation) but one needs to understand the other underlying quirks to do so.
- UweSchmidt 12y agoYes, it's parseInt() plus some further checks if the results are within an expected range in my code. And overall being more verbose, explicit, and careful. And the occasional squinting eyes from the "Fry meme".
- LukeB_UK 12y agoParseInt accepts a second parameter for the radix, it's use is highly encouraged.