In Javascript there are two ways to convert types:
1) JS conversion function
2) JS does it implicitly
1) Using Functions:
| From\To | Object | Date | Number | Array | String | Boolean |
| Object | \ | Already an object | valueOf() | valueOf() | valueOf() | valueOf() |
| Date | Already an object | \ |
Number([date]) getTime() |
N/A |
toString() String([date]) |
N/A |
| Number | Not good practice |
new Date(ms) |
\ | N/A |
toString([base]) toExponetial() toFixed() toPrecision() String([number]) |
Boolean([number]) |
| Array | Not good practice | N/A | reduce() | \ |
join([delimiter]) reduce() |
every() some() reduce() |
| String | Not good practice | new Date(str) |
Number([string]) parseInt([string]) parseFloat([string]) unary + operator |
split([delimiter]) for(... of ...) |
\ | Boolean([string]) |
| Boolean | Not good practice | N/A | Number([boolean]) | N/A |
toString() String([boolean]) |
\ |
2) Automatic conversion:
When trying to output a variable to HTML, JS will automatically call the toString() method.
E.g. document.getElementById("demo").innerHTML = myVar;
Using operators between different types will also automatically convert them.
E.g. "5" + 5 = "55"
Also calling if statements will automatically try to convert them to boolean
E.g. if(myVar) // here the variable is forced to become a boolean
Automatic conversions in general:
Conversions to boolean: 0, empty, undefined, null, elements are converted to false. The rest are converted to true.
Conversions to string: most elements will convert to how they look, aside from empty arrays and strings will be simply empty string -- ""
Conversions to number: most strings will be parsed correctly if they're valid numbers i.e. "100", NaN if they're not i.e. "apple". Empty, false, null will be converted to 0, undefined and arrays which cannot be properly parsed will be NaN.
If in doubt it's probably best to do a quick experiment in the browser.