DEV Community

Cover image for parseInt() For Beginners
YarixaR
YarixaR

Posted on

parseInt() For Beginners

This is for anyone that's newly immersing themselves in the world of coding. If you are a beginner-level coder like me, you've looked into parseInt() and became completely lost when it came to the "radix" part. Here is my simplest explanation of what the function parseInt does.

What is parseInt?

parseInt is a function that can take 2 arguments and it can either return an integer or a NaN (not a number).

This is the syntax:

parseInt(string)
or
parseInt(string, radix)

Assuming you know all the different data types, for example:

  1. numbers
  2. strings
  3. booleans
  4. symbols
  5. objects
  6. null
  7. undefined

Then you already know that JavaScript will perform addition to a number data type.

1 + 2 + 3;
//6
Enter fullscreen mode Exit fullscreen mode

Adding a string to a number, Javascript will pair them together and will return a string. It cannot perform addition.

'1' + 2 + 3
// '123'
Enter fullscreen mode Exit fullscreen mode

Now consider this example:

before parseInt
What's happening above is JavaScript does not see '5' as a number but as a string. We're asking the string to add 1 but instead of creating a new value, it will add the 1 next to the string. If your goal is to convert a string into a number, that's when you'd use parseInt.
parseInt function

parseInt will remove the quotes from the string before performing the addition or any form of operation. Thus resulting in a whole integer.
If ever you need a floating integer (a number with a decimal) to convert into a whole number, parseInt can arrange that for you as well.

const num = 10.03
console.log(parseInt(num));

//  10
Enter fullscreen mode Exit fullscreen mode

parseInt(string, radix)

Traditionally, parseInt should take 2 arguments. The function parses (analyzes) a string and returns an integer of the specified radix.

What is a radix?

A radix is the base in mathematical numeral systems. When using parseInt, you will want to work with the base 10 because it uses the ten digits from 0 through 9. This is called the decimal system.

parseInt("4", 10)
// 4

parseInt("4.444", 10)
// 4

parseInt("Jerry is 9", 10)
// NaN

Enter fullscreen mode Exit fullscreen mode

The last thing you need to know is NaN. This function can only read the first value starting the string. If it's not a number, it will return as NaN.

Source:
“Radix.” Wikipedia, Wikimedia Foundation, 23 June 2022, https://en.wikipedia.org/wiki/Radix.

“Parseint() - Javascript: MDN.” JavaScript | MDN, https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt.

Top comments (0)