How to Convert String into Integer in JavaScript?

To convert a string value into an integer we can use the parseInt() function in JavaScript. It accepts two parameters in which the first is required and the second is optional.

Let’s suppose we have a variable that has a string value that needs to convert into an integer.  Before converting it into an integer, let’s check its type.

let birds = "20";
console.log(typeof birds);
// Output: 'string'

In JavaScript, the typeof operator is used to check the variable’s type. In the above script, we checked birds variable type through the typeof operator which returns string.

Next, let’s convert birds variable value into an integer. To do that pass the birds variable as an argument into parseInt() function and assign its result to convertIntoInteger variable.

// convert string into integer
let convertIntoInteger = parseInt(birds);
// Output: 20

In the above script, the parseInt() function converted the birds variable value into an integer. We can check the converted value’s type by using typeof operator.

console.log(typeof convertIntoInteger);
// Output: 'number'

Related Posts