Can anyone explain how the parseInt() functions works and what the Radix Parameter is?
As a case study, I am trying to get to grips with this code snippet:
var maxChars = parseInt( formField.attr('maxlength') ? formField.attr('maxlength') : counter.text() );
Can you also explain how this code works? Why is formField.attr('maxlength') there twice? I find the use of operators here pretty darn confusing!
How does the Radix Parameter work in this example?
The parseInt method parses a value as a string and returns the first integer. A radix parameter specifies the number system to use: 2 = binary, 8 = octal, 10 = decimal, 16 = hexadecimal. If radix is omitted, JavaScript assumes radix 10. If the value begins with "0x", JavaScript assumes radix 16.
parseInt takes two parameters, the second one is optional. String and Radix. String is the value to parse. If the value provided is not a string it will convert it to a string.
What will be the radix value of the parseInt() method when the string begins with 0? Explanation: If the string begins with 0x, then the radix value will be 16. If the string begins with “0”, the radix is 8 (octal).
The parseInt function converts its first argument to a string, parses that string, then returns an integer or NaN . If not NaN , the return value will be the integer that is the first argument taken as a number in the specified radix .
The radix
is another name for base
, i.e. 2 for binary, 10 for decimal, 16 for hexadecimal, explained in more detail on the Mozilla Developer Network site.
In your example there is no radix parameter, so the interpreter will fall back to the default behaviour, which typically treats numbers as decimal, unless they start with a zero (octal) or 0x
(hexadecimal).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With