Code Logo

Parse Integer with parseInt()

Published at25 Jul 2026
JavaScript Functions Easy 0 views
Like0

Write a JavaScript function that takes a string representation of a number and a radix (base), and returns the parsed integer using parseInt() with the radix parameter. The radix specifies the numeral system to use: 2 for binary, 8 for octal, 10 for decimal, 16 for hexadecimal.

The parseInt() function in JavaScript parses a string argument and returns an integer of the specified radix. The radix parameter is critical to specify because without it, parseInt() can produce unexpected results: strings starting with "0x" are parsed as hexadecimal, while others may be parsed as octal in older browsers. Always specifying the radix (typically 10) is a best practice.

Unlike Number() or unary + operator which convert the entire string, parseInt() parses until it encounters an invalid character and returns the integer parsed so far. This makes it useful for extracting numbers from strings with trailing non-numeric characters like "42px".

Time complexity is O(n) where n is the string length. The function ignores leading whitespace and stops at the first non-numeric character for the given radix. Returns NaN if the first non-whitespace character cannot be converted.

Edge cases include strings starting with non-numeric characters (returns NaN), empty strings (returns NaN), radix values outside the range 2-36 (returns NaN), and strings with leading zeros or whitespace.

Example Input & Output

Example 1
Input
"1010",2
Output
10
Explanation

Binary 1010 = 10

Example 2
Input
"42px",10
Output
42
Explanation

Stops at non-numeric

Example 3
Input
"10",10
Output
10
Explanation

Decimal parse

Example 4
Input
"ff",16
Output
255
Explanation

Hexadecimal FF = 255

Example 5
Input
"77",8
Output
63
Explanation

Octal 77 = 63

Algorithm Flow

Recommendation Algorithm Flow for Parse Integer with parseInt()
Recommendation Algorithm Flow for Parse Integer with parseInt()

Solution Approach

function solution(str, radix) {
  return parseInt(str, radix);
}

Best Answers

javascript - Approach 1
function solution(str, radix) {
  return parseInt(str, radix);
}