When the type of a variable is changed to another type, it is known as type conversion or type casting.
JavaScript does not have float
, Int
, double
, or long
types like other languages such as C, C++, and Java. Instead, it has a common type for all numerical values: Number
. Hence, type conversion is needed so that the right operation can be formed for a certain variable.
Let’s convert a String
type variable to a Number
type variable. We will also see that performing the add (+
) operation has a different effect on variables before conversion and after conversion.
To convert a String
variable into a Number
, we will use the JavaScript global method Number()
.
Number()
takes one parameter of string
type.
Number()
will return a value of Number
type, or NaN
if the string is not valid or does not contain a numeric value.
var a = "3.12";console.log(typeof(a));console.log(a + 3);var a = Number(a);console.log(typeof(a), " value ", a + 3);
The example above shows how to do a type conversion. It’s a simple but useful thing to know while working code.
In line 1, we declare a variable of string
type. Writing a character in quotes (""
/''
) will treat the variable as string.
In line 3, we check the type of variable using the typeOf()
method and print it using console.log()
.
In line 5, we perform an add operation on the variable.
In line 7, we convert the string
to Number
using global method Number()
.
In line 9, we again check the type of variable a
and perform an add operation on it, and then print it on console.
As we can see, the first line of output indicates that the variable was a string. When we perform the add operation it, we append the number 3
to the string 3.12
.
But the result we wanted was 6.12
. After using the global method, Number()
, the result we get in the last line is Number
. This means we have successfully achieved type conversion, and the result we wanted, 6.12
, is returned.
Number()
?If an invalid string,
a string which contains alphabets or symbols, is passed to Number()
, then the method will convert it to NaN
(Not a Number).
The code below is an example showing if the string passed is not a valid number.
var a = "33 asd 12";var b = Number(a);console.log(b);