Type conversion is the process of converting a value from one data type to another (such as a string to a number). In JavaScript, this happens in two ways: Explicit (done manually by the developer) and Implicit (done automatically by JavaScript).
Explicit conversion occurs when you manually use a JavaScript function to change a value's type.
The global Number() method can convert strings or booleans to numbers.
Number("3.14") // returns 3.14
Number(" ") // returns 0
Number("") // returns 0
Number("99 88") // returns NaN (Not a Number)
Number(true) // returns 1
Number(false) // returns 0
The global String() method or the toString() method can convert
numbers or booleans to strings.
String(123) // returns "123"
(100 + 23).toString() // returns "123"
String(false) // returns "false"
JavaScript is a very flexible language. If you try to operate on two different data types, JavaScript will often automatically convert one of them to make the operation work. This is called type coercion.
When adding a number and a string, JavaScript treats the plus sign as a concatenation operator and converts the number to a string.
let result = "5" + 2;
console.log(result); // "52" (String)
Interestingly, for subtraction (-), multiplication (*), and
division (/), JavaScript will convert the string to a number.
console.log("10" - 5); // 5 (Number)
console.log("10" * "2"); // 20 (Number)
console.log("10" / 2); // 5 (Number)
| Original Value | Converted to Number | Converted to String | Converted to Boolean |
|---|---|---|---|
false |
0 | "false" | false |
true |
1 | "true" | true |
0 |
0 | "0" | false |
1 |
1 | "1" | true |
"0" |
0 | "0" | true |
null |
0 | "null" | false |
undefined |
NaN | "undefined" | false |
Number())+ operator favors strings-, *, and / operators favor
numbersnull convert to 0 when forced into a
number contextundefined converts to NaN in a number context