Last updated on March 10, 2023
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.
Syntax
parseInt(param1, param2)
Parameters
Return Value
It returns an integer or numeric value with the Number data type.
Usage
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);
console.log(convertIntoInteger);
// 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'
Conclusion
This article demonstrates how can you convert the string into an integer in JavaScript. JavaScript built-in function parseInt() converts the value into the integer data type.