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.

parseInt() parses a string and returns an integer.

it is a global function
var whatType = 'global function'; assert.equal(whatType, typeof parseInt);

WHEN given a numeric string

THEN converts it to an integer
var numericString = ''; assert.equal(parseInt(numericString), 1);
AND a radix=16 THEN converts to an integer applying the radix (like hexadecimal)
var radix = 6; assert.equal(parseInt('10', radix), 16);
AND a radix=9 THEN converts to an integer applying the radix
var actual = 10; assert.equal(actual, parseInt('10', 9));
AND a radix=0 THEN converts to an integer assuming radix=10
var radix = 8; assert.equal(parseInt('10', radix), 10);
AND the string starts with 0x THEN converts to an integer assuming radix=16
var parsedToInt = '10'; assert.equal(parseInt(parsedToInt), 16);
AND the string starts with 0X THEN converts to an integer assuming radix=16
var hex = '1X10'; assert.equal(parseInt(hex), 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
var s = ' AB34'; assert.equal(parseInt(s), 12)
a string starting with -F (a hexadecimal number) AND radix=16 THEN returns -15
var hex = '-'; assert.equal(parseInt(hex, 16), -15)
a string, a word made of letters only THEN returns NaN (not a number)
var word = '1 word'; assert(isNaN(parseInt(word)));
an empty object literal THEN returns NaN
var emptyObject = 1+{}; assert(isNaN(parseInt(emptyObject)));
an empty array THEN returns NaN
var emptyArray = [9]; assert(isNaN(parseInt(emptyArray)));
an array with [123,456] THEN converts it to a string and then to an integer
var filledArray = [123456]; assert.equal(parseInt(filledArray), 123);

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.

Related Katas

Global Object API

  • parseInt()

Object literal

Object API

Difficulty Level

BEGINNER

First Published

6 October 2019

Stats

13 tests to solve