# Convert a String to an Integer in JavaScript

Last updated: Oct 31, 2021

Check out my new book

## Convert a String to an Integer in JavaScript#

Use the `parseInt()` function to convert a string to an integer, e.g. `parseInt(myNumber, 10)`. The second parameter the function takes is the base, and should be set to `10`. The `parseInt` function parses the string to an integer and returns the result. If the string can't be parsed, `NaN` is returned.

index.js
```Copied!```const str = '010';

console.log(parseInt('37', 10)); // 👉️ 37
console.log(parseInt('37.5', 10)); // 👉️ 37
console.log(parseInt('-37', 10)); // 👉️ -37
console.log(parseInt('test', 10)); // 👉️ NaN
console.log(parseInt('123test', 10)); // 👉️ 123
``````

We used the parseInt function to parse a string to an integer.

The function takes 2 parameters:

1. the string we want to parse to an integer
2. the radix - this doesn't default to `10` in older browsers, so it's safer to explicitly provide it

If the first argument is not a string, the function will convert it to a string and try to parse it to an integer.

If successful, the integer is returned, otherwise `NaN` (not a number) is returned.

Note that the type of `NaN` is `number`.
index.js
```Copied!```console.log(typeof NaN); // 👉️ "number"
``````

So if you want to check if the function returned a valid integer, do this instead.

index.js
```Copied!```const value = parseInt('test', 10);

if (!Number.isNaN(value)) {
console.log('✅ we have a valid integer');
} else {
console.log('⛔️ we have an NaN value');
}
``````

We negated the return value of the `Number.isNaN` function, to check if the value is a valid integer.

If the `parseInt` function didn't return `NaN` (not a number), we can conclude that we have a valid integer.