Published on

TLDR: JavaScript parseInt Method


parseInt is a built-in JavaScript method used to parse a string into a number

It takes two parameters: the string to parse and the radix (base in numerical systems).

// Ignores ignores non-numeric characters
parseInt(' 10') // 10
// ignores any non-numeric characters after the number as well
parseInt('10 hello') // 10
// + or - signs are supported
parseInt('-10') // -10

// NaN is returned if string is not valid  or does not contain number
parseInt(' hello10') // NaN


You can pass radix number to parse binary or hexadecimal string

// binary
parseInt('1010', 2) // 10

// parsing hexadecimal string
parseInt('AA', 16); // 170

To avoid unexpected results, always set the radix to 10 in parseInt method (unless parsing binary or hexadecimal) because it assumes the strings that starts with 0x or 0X are hexadecimal unless radix is explicitly set

parseInt('0x10'); // 16
parseInt('10');   // 10

Happy understanding Javascript!