use parseInt() in JavaScript

in this post, I will explain about the parseInt function in JavaScript. how to use parseInt() in JavaScript. parseInt() parses a string and returns as an integer or NaN.

The main purpose of use the parseInt function is to extract number from a string. it returns value to an actual number.

Syntax :

parseInt(string)

Example :

const checkNumber = '15';
console.log(5 + checkNumber);  // returns 515

In above example, 15 is a string and not an actual number. when I will add 5 to the string then it given 515 because we are just adding 5 to a string that is just like form of a number.

Example parseInt() :

const checkNumber = '15';
console.log(5 + parseInt(checkNumber));  // returns 20

the function parseInt() has removed 15 from the string and converted it to an actual number.
parseInt function can either return an integer or NaN. So when I will get a NaN value I am explaining in below example .

Example :

const checkNumberWithString = 'year is 2022';
console.log(parseInt(checkNumberWithString));
// returns NaN

when we have some text before a number with string. like “year is 2022” so it will return a NaN value because the parseInt function only looks at the first value starting the string. If the value is not a number, NaN is returned.

Leave a Reply

Your email address will not be published. Required fields are marked *

+ 50 = 60