Implement parseInt

What's going on under the hood


> [] + []
    = String([]) + String([])
    = [].join() + [].join()
    = '' + ''

> {} + []
    = {/*empty block */}; +[]
    = Number([])
    = Number(String([]))
    = Number('')
    = 0

> x = ['30', '20', '10']
> x.map(parseInt)
    = [
        parseInt('30', 0),
        parseInt('20', 1),
        parseInt('10', 2)
    ]
    = [10, NaN, 2]
						
The parseInt function converts its first argument to a string, parses it, and returns an integer or NaN. If not NaN, the returned value will be the integer that is the first argument taken as a number in the specified radix (base). For example, a radix of 10 indicates to convert from a decimal number, 8 octal, 16 hexadecimal, and so on. For radices above 10, the letters of the alphabet indicate numerals greater than 9. For example, for hexadecimal numbers (base 16), A through F are used.

If parseInt encounters a character that is not a numeral in the specified radix, it ignores it and all succeeding characters and returns the integer value parsed up to that point. parseInt truncates numbers to integer values. Leading and trailing spaces are allowed.

Because some numbers include the e character in their string representation (e.g. 6.022e23), using parseInt to truncate numeric values will produce unexpected results when used on very large or very small numbers. parseInt should not be used as a substitute for Math.floor().

If radix is undefined or 0 (or absent), JavaScript assumes the following:
  • If the input string begins with "0x" or "0X", radix is 16 (hexadecimal) and the remainder of the string is parsed.
  • If the input string begins with "0", radix is eight (octal) or 10 (decimal). Exactly which radix is chosen is implementation-dependent. ECMAScript 5 specifies that 10 (decimal) is used, but not all browsers support this yet. For this reason always specify a radix when using parseInt.
  • If the input string begins with any other value, the radix is 10 (decimal).
  • If the first character cannot be converted to a number, parseInt returns NaN.
For arithmetic purposes, the NaN value is not a number in any radix. You can call the isNaN function to determine if the result of parseInt is NaN. If NaN is passed on to arithmetic operations, the operation results will also be NaN.
To convert number to its string literal in a particular radix use intValue.toString(radix).