3 ms·
There's an important distinction between this code and the Math.random() casting that you posted earlier (http://news.ycombinator.com/item?id=2472223 http://new
by nbpoole 15y ago
There's an important distinction between this code and the Math.random() casting that you posted earlier (http://news.ycombinator.com/item?id=2472223 http://news.ycombinator.com/item?id=2472223 in case anyone missed it).
With parseInt, we're talking about best practices: if you fail to specify the radix, your code may yield unexpected results (eg: parsing a number with a leading 0 may cause parseInt to assume an octal base). On the other hand, your code may still work fine if your inputs are properly formatted. In that case, specifying the radix just enhances readability.
With casting Math.random(), what you saw was an actual bug: people were using 0's in their code when they thought they were getting random integers. Unless the code was being written for an obfuscated Java contest, I'd wager it was buggy.
- tolmasky 15y agoNot sure why you don't think the missing radix is a "real" bug, there are plenty of real use cases where a leading zero is proper formatting, for example, in spreadsheets that keep the same number of digits in each cell. Not to mention that since this is all web code there is a good chance this is all user input so anything goes.
- nbpoole 15y agoMy point is that specifying the radix is a best practice: there are still a number of situations where it's unnecessary for properly functioning code (ie: if you aren't using zero-padded numbers). Specifying the radix certainly helps readability, but you can't just do a regex search and say that all the code it finds is buggy. On the other hand, casting Math.random() to an int is wrong unless you're trying to express 0 in an obfuscated way.
- podperson 15y agoAgreed. If you're calling parseInt on a variable it's simply not a bug. parseInt(1) seems like a whole different class of bug to me :-)
- antimatter15 15y agoWell, say you're trying to get an int from .style.top, it'll never have leading zeroes.
- tpope 15y agoThere are also real use cases where octal and hex parsing are desired. To do a search for parseInt\(*[^,]\) and declare all as bugs is myopic.