jskatas.org Continuously Learn JavaScript. Your Way.

Global Object API: parseInt()

parseInt() converts a given value to a string and then tries to make an integer out of it.

Donate to NGO Julenka. Support Ukranians in need. Julenka is an NGO which my brother founded in 2011 to support Ukranian families and kids in need.

parseInt() parses a string and returns an integer.

  • it is a global function

WHEN given a numeric string

  • THEN converts it to an integer
  • AND a radix=16 THEN converts to an integer applying the radix (like hexadecimal)
  • AND a radix=9 THEN converts to an integer applying the radix
  • AND a radix=0 THEN converts to an integer assuming radix=10
  • AND the string starts with 0x THEN converts to an integer assuming radix=16
  • AND the string starts with 0X THEN converts to an integer assuming radix=16

WHEN given a NOT-numeric string (it will be tried to be converted to a string)

  • a string starting with numbers THEN converts containing the leading numbers only
  • a string starting with -F (a hexadecimal number) AND radix=16 THEN returns -15
  • a string, a word made of letters only THEN returns NaN (not a number)
  • an empty object literal THEN returns NaN
  • an empty array THEN returns NaN
  • an array with [123,456] THEN converts it to a string and then to an integer

Links

The very first version of the spec defining `parseInt`, the ES1 spec.
A later, newer version of the spec text for `parseInt`, from ES10.
The description of `parseInt()` on MDN, probably best to read.
Announcement of this kata on twitter.