4 ms·
Sorry, but that advice about number.toString(radix) is mistaken. JSHint does not complain if you omit the radix in a number.toString() call, nor should it. The
by Stratoscope 14y ago
Sorry, but that advice about number.toString(radix) is mistaken.
JSHint does not complain if you omit the radix in a number.toString() call, nor should it. The default radix value for number.toString() is 10, and there are no magical surprises as there are with parseInt(). If you write number.toString() it means exactly the same thing as number.toString(10). There is no reason to provide an explicit radix of 10 unless you just like it better than way.
In the (016).toString() example, the problem isn't the missing radix; (016).toString(10) returns the same value, "14". The problem is the 016 constant itself. That is an octal constant and has already been converted to decimal 14 before the .toString() call. There is nothing that .toString() can do to fix this problem.
Now you're right that it is useful for a developer to know about the radix parameter, so you can easily convert a number to its string representation in hex or binary or whatever base you need.
parseInt() is a different story, of course. You are quite correct that you should never write parseInt(number) without a radix argument, unless you actually want the behavior of a leading zero making it octal and a leading 0x making it hexadecimal.
(edited for clarity)
- jakub_g 14y agoI must admit you're right with the first part. I haven't thought twice nor checked things. Thanks for pointing it out. Regaring parseInt(), the story is even more complex though :) You should never use it without the radix because that behavior is not reliable when it comes to implying octal representation. Calling parseInt("016") yields 16 in Chrome (ES5 compliant [1]), while 14 in Firefox, Opera and IE8. [1] https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/parseInt https://developer.mozilla.org/en-US/docs/JavaScript/Referenc...
- Stratoscope 14y agoOh wow, you're right about parseInt(). For some reason I thought the octal thing was standard across browsers. That's what I get for adding that throwaway comment at the end without checking it. Thanks for catching that!