Introduction
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
Type conversion which is performed automatically by the JavaScript interpreter is known as implicit type conversion or coercion. Implicit type conversion may take place when the expected type is different from the actual type of the value given from the user or read from a file etc. For example, consider the following expression:
“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.
Suryateja Pericherla, at present is a Research Scholar (full-time Ph.D.) in the Dept. of Computer Science & Systems Engineering at Andhra University, Visakhapatnam. Previously worked as an Associate Professor in the Dept. of CSE at Vishnu Institute of Technology, India.
He has 11+ years of teaching experience and is an individual researcher whose research interests are Cloud Computing, Internet of Things, Computer Security, Network Security and Blockchain.
He is a member of professional societies like IEEE, ACM, CSI and ISCA. He published several research papers which are indexed by SCIE, WoS, Scopus, Springer and others.
Leave a Reply