Type Conversion in JS

Type Conversion in JS

Javascript has loosely typed language or dynamic type language. It automatically converts the data into the right type, but it creates problems when we work on calculation-related applications. When we use the + operator it gives the wrong output it does not add values of input instead of it concatenates the values of input and gives the wrong output.

Javascript provides a number of ways to convert data from one type to another type but there is two most common type conversion:

  • Numeric Conversion
  • String Conversion


Numeric Conversion: It is used to convert data into a number format. There are two methods available in js to convert data into numbers which are the following:

  • parseInt(): It is used to convert data into integer format. It does not contain decimal numbers.
var a=”5”;
var b=parseInt(a);

b will return numeric 5.


  • parseFloat): It is used to convert data into decimal format.
var a=’5.5’;

b will give decimal format.


Example:  Find the largest of three number

<!DOCTYPE html>
<input type="text" id="num1">
<input type="text" id="num2">
<input type="text" id="num3">
<button type="button" onclick="check()">check</button>
function check()
   var num1 = parseInt(document.getElementById("num1").value);
   var num2 = parseInt(document.getElementById("num2").value);
    var num3 = parseInt(document.getElementById("num3").value);
   if(num1>num2 && num1>num3)
     alert("num1 is greatest");
   else if(num2>num1 && num2>num3)
     alert("num2 is greatest");
   else if(num3>num1 && num3>num2)
     alert("num3 is greatest");
     alert("invalid input");

Here in this example, we have used the parseInt() method to convert input value into integer format.

Note: text input always gives value in string format so you should keep in mind to convert input value in integer format if you want to perform calculation, condition,s, etc.


String Conversion: It is used to convert data into string format. There are two functions available in JS which are following:

  • String()
  • toString()
Example: String() Function
Syntax:  String(value);
var a=5;
var b=String(a);

b will return “5” in string format.


Example:  toString() function
Syntax: variablename.toString();
var a=”5”;
var b=a.toString();

b will return “5” in string format.