In programming, type conversion is the process of converting data of one type to another. For example: converting String data to Number.
There are two types of type conversion in JavaScript.
- Implicit Conversion - automatic type conversion
- Explicit Conversion - manual type conversion
JavaScript Implicit Conversion
In certain situations, JavaScript automatically converts one data type to another (to the right type). This is known as implicit conversion.
Example 1: Implicit Conversion to String
Note: When a number is added to a string, JavaScript converts the number to a string before concatenation.
Example 2: Implicit Conversion to Number
Example 3: Non-numeric String Results to NaN
Example 4: Implicit Boolean Conversion to Number
Note: JavaScript considers 0 as false and all non-zero number as true. And, if true is converted to a number, the result is always 1.
Example 5: null Conversion to Number
Example 6: undefined used with number, boolean or null
JavaScript Explicit Conversion
You can also convert one data type to another as per your needs. The type conversion that you do manually is known as explicit type conversion.
In JavaScript, explicit type conversions are done using built-in methods.
Here are some common methods of explicit conversions.
1. Convert to Number Explicitly
To convert numeric strings and boolean values to numbers, you can use Number(). For example,
In JavaScript, empty strings and null values return 0. For example,
If a string is an invalid number, the result will be NaN. For example,
Note: You can also generate numbers from strings using parseInt(), parseFloat(), unary operator + and Math.floor(). For example,
2. Convert to String Explicitly
To convert other data types to strings, you can use either String() or toString(). For example,
Note: String() takes null and undefined and converts them to string. However, toString() gives error when null are passed.
3. Convert to Boolean Explicitly
To convert other data types to a boolean, you can use Boolean().
In JavaScript, undefined, null, 0, NaN, '' converts to false. For example,
All other values give true. For example,
JavaScript Type Conversion Table
The table shows the conversion of different values to String, Number, and Boolean in JavaScript.
| Value | String Conversion | Number Conversion | Boolean Conversion |
| 1 | "1" | 1 | true |
| 0 | "0" | 0 | false |
| "1" | "1" | 1 | true |
| "0" | "0" |
0 | true |
| "ten" | "ten" |
NaN |
true |
true |
"true" | 1 | true |
false |
"false" | 0 | false |
null |
"null" | 0 | false |
undefined |
"undefined" | NaN |
false |
| '' | "" | 0 | false |
| ' ' | " " | 0 | true |
You will learn about the conversion of objects and arrays to other data types in later tutorials.
Related Examples: