How to Convert String into Integer in JavaScript?

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

  • Parameter 1: It is required, and the function expects the value to be a string.
  • Parameter 2: It is optional, default value is 10.

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.


Written by
I am a skilled full-stack developer with extensive experience in creating and deploying large and small-scale applications. My expertise spans front-end and back-end technologies, along with database management and server-side programming.

Share on:

Related Posts