The mechanism of converting a value or variable from one type to another type is known as type conversion. There two types of type conversion: implicit type conversion and explicit type conversion.
Implicit Type Conversion
“John” + 123
It can be observed that in the above expression, + is a concatenation operator. So, even though the second operand is a number, it will be converted (implicit conversion) to a string and will be concatenated with “John”. Now, consider the following example:
8 * “2”
The * operator is only applicable on numbers. So, the second operand will be converted from a string to a number and the resultant value will be 16.
Boolean false will be equal to 0 and true will be equal to 1 when converted to number. Both null and undefined will become false when converted to Boolean. A number 0 will be converted to false and any other number will be converted to true, when it is converted to a Boolean.
Explicit Type Conversion
Sometimes there is a need for the programmer to force type conversion. Such conversion specified by the programmer is known as explicit type conversion or type casting. For example, a number can be casted to a string using the String constructor as shown below:
var str = String(5);
We can also cast a number to String using the toString( ) method which provides an advantage of specifying the base of the number. Consider the following expressions:
var x = 5;
var y = x.toString( );
var z = x.toString(2); //2 specifies the base of the result. 5 in base 2 is 101
In the above expressions, y will have the string “5” and z will have the string “101”.
A string can be casted to a number using the Number constructor as shown below:
var x = Number(“10”);
The above code works only when the supplied string parameter does not contain any other characters after the number. To convert a string which contains a number at any position, we can use parseInt( ) and parseFloat( ) methods.