JavaScript has a type conversion mechanism that can explicitly or implicitly convert a value of one data type to a value of another data type. Type conversion is a method of converting one data type to another. Type conversion is often used when building applications with Javascript.
JavaScript has two types of type conversions.
Implicit conversions are type conversions that happen automatically when converting to or returning from a functionType call. Implicit type conversion occurs automatically when an operation is performed between values of different data types, such as adding a number to a string.
Example:
Output:
510
In the example above, the string value a is implicitly converted to a number when added to b.
An Explicit type conversion is when you explicitly request that a value be converted to a specific type. A type conversion performed manually by some function or method. The following methods are available for explicit type conversion in JavaScript.
- String(): Convert value to string.
- Number(): Converts a value to a number.
- Boolean(): Convert value to boolean.
- parseInt(): Convert string to integer.
- parseFloat(): Converts a string to a hexadecimal number.
Example:
Output:
15
In the example above, the string value a is explicitly converted to a number using the Number() function, and the result of the addition operation is the expected number 15.