Last updated on October 2, 2022 by Ayaz Ali Shah
Number: Numbers are 0 to 10 or uncountable numeric digits. In this data type, we are not allowed to add commas, dots, and any other special character. Numbers can be calculated with arithmetic operators.
String: string can be a text and number but cannot calculate.
In this article, we will learn about the
parseInt() is a function that converts a string to an integer. An integer is a numeric digit without a comma or dot. You can calculate the numbers but if a number’s type is a string then it cannot be calculated.
parseInt() method accepts two parameters (string, radix), if a number has a string type then we can use the parseInt function to convert it into an integer.
var numberInString = '123'; console.log(numberInString + 2); // Output 1232
In the above example, we have a number value with a string type that cannot be calculated. We tried to sum both values through an arithmetic operator but we got concatenated value in the result. It is because
numberInString variable has a numeric value with string type.
Now let’s see the below example,
var numberInString = '123'; console.log(parseInt(numberInString) + 2); // Output 125
In the above, we used the
parseInt() method to convert the
numberInString value into an integer. After converting it into an integer we summed it through an arithmetic operator which returns the expected result.
If we pass an alphanumeric value as an argument in the
parseInt() method then it would return
NAN. In the below example, you can see variable ticket has a string that contains two words first Number and 50. That’s why the
parseInt() method returns
const ticket = 'Number 50'; console.log(parseInt(ticket)); // returns NaN
In this article, we learned how to use the