When JavaScript tries to operate on a "wrong" data type, it will try to convert the value to a "right" type.
The result is not always what you expect:
5 + null // returns 5 because null is converted to 0
"5" + null // returns "5null" because null is converted to "null"
"5" + 2 // returns "52" because 2 is converted to "2"
"5" - 2 // returns 3 because "5" is converted to 5
"5" * "2" // returns 10 because "5" and "2" are converted to 5 and 2
"5" + null // returns "5null" because null is converted to "null"
"5" + 2 // returns "52" because 2 is converted to "2"
"5" - 2 // returns 3 because "5" is converted to 5
"5" * "2" // returns 10 because "5" and "2" are converted to 5 and 2
Automatic String Conversion
JavaScript automatically calls the variable's toString() function when you try to "output" an object or a variable:
document.getElementById("demo").innerHTML = myVar;
// if myVar = {name:"Fjohn"} // toString converts to "[object Object]"
// if myVar = [1,2,3,4] // toString converts to "1,2,3,4"
// if myVar = new Date() // toString converts to "Fri Jul 18 2014 09:08:55 GMT+0200"
// if myVar = {name:"Fjohn"} // toString converts to "[object Object]"
// if myVar = [1,2,3,4] // toString converts to "1,2,3,4"
// if myVar = new Date() // toString converts to "Fri Jul 18 2014 09:08:55 GMT+0200"
Numbers and booleans are also converted, but this is not very visible:
// if myVar = 123 // toString converts to "123"
// if myVar = true // toString converts to "true"
// if myVar = false // toString converts to "false"
// if myVar = true // toString converts to "true"
// if myVar = false // toString converts to "false"
JavaScript Type Conversion Table
This table shows the result of converting different JavaScript values to Number, String, and Boolean:
| 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 |
| "000" | 0 | "000" | true |
| "1" | 1 | "1" | true |
| NaN | NaN | "NaN" | false |
| Infinity | Infinity | "Infinity" | true |
| -Infinity | -Infinity | "-Infinity" | true |
| "" | 0 | "" | false |
| "20" | 20 | "20" | true |
| "twenty" | NaN | "twenty" | true |
| [ ] | 0 | "" | true |
| [20] | 20 | "20" | true |
| [10,20] | NaN | "10,20" | true |
| ["twenty"] | NaN | "twenty" | true |
| ["ten","twenty"] | NaN | "ten,twenty" | true |
| function(){} | NaN | "function(){}" | true |
| { } | NaN | "[object Object]" | true |
| null | 0 | "null" | false |
| undefined | NaN | "undefined" | false |
Values in quotes indicate string values.
Practice Excercise Practice now