Why is it recommended to provide an extra radix parameter to parseInt ()?

I've always used a function parseInt()

in Javascript without passing the radix parameter. According to the MDN documentation here , he stated that not providing this parameter could lead to unpredictable behavior.

Always specify this parameter to eliminate reader confusion and ensure predictable behavior.

Can anyone clarify what this unpredictable behavior means with some code examples?

+3


source to share


3 answers


In older versions of the language, the parseInt()

function will obey the usual JavaScript numeric constant syntax, including recognition of a leading zero for octal constants and a leading 0x for hexadecimal constants. Thus, unless your code explicitly insisted on base 10, then roaming (possibly user supplied) numbers with leading zeros would be interpreted as base-8 values ​​and leading 0x as hex.

The base-8 behavior has gone since ES5.1 (I think it may have been before), but the base 16 behavior still exists. (Probably leading 0x is slightly less common than random prefix than plain 0 output.)

My experience looking at code here on Stack Overflow is that parseInt()

it is used anyway. It is usually easier to convert strings (often, strings taken from DOM element properties .value

) to numbers with a unary operator +

:

var count = +document.getElementById("count").value;

      



This won't necessarily give you an integer, of course. However, what it will do is note that the input string has trailing non-numeric garbage. The function parseInt()

just stops parsing a string like "123abc" and gives you 123

a numeric value. However, the leader +

will give you NaN

.

If you want whole numbers, you can always use Math.floor()

or Math.round()

.

edit - The comment notes that ES2015 requires leading 0o

or 0o

"strict" mode for octal literals, but this is not the case parseInt()

, which (in ES2015) only overrides the base default for hexadecimal strings.

+4


source


Without giving a reason, it parseInt

tries to determine what the correct radius is by the value you pass, for example if the value starts 0x

, then it dictates that you should pass in hex values. The same applies to 0

(octal).

This becomes problematic when your input has zero padding but no radix support. If the result is (possibly) not as expected



console.log(parseInt(015))
      

Run codeHide result


0


source


For some reason best known to themselves, the folk defining the behavior of this function sets the radix parameter as the default, but then decided to leave the default until implementation! (It might have been prudent to insist on a value of 10, but it might have upset popular progammy in the 1970s who still believed octal literals were useful.)

So, for reliable programming you need to provide the radix parameter.

-1


source







All Articles