In this article, we'll be discussing type conversions and how you can use them to convert between various types.
Convert to boolean
alert(Boolean(0) === true); // false alert(Boolean(1) === true); // true
alert(Boolean("") === true); // false alert(Boolean(null) === true); // false alert(Boolean(undefined) === true); // false alert(Boolean("hello") === true); // true alert(Boolean("000") === true); // true
Convert to number
Sometimes you need to ensure that you're dealing with numeric values. For instance, if you take input from the user, e.g. through the browser-based function prompt(), you will get a string back, even if a number is entered. This will lead to unexpected results if you try to do math with the input, as illustrated by this example:
let n1 = 40; // Example input: 2 let n2 = prompt("Please enter a number:"); // Example output: 402 alert(n1 + n2);
let n1 = 40; // Example input: 2 let n2 = Number(prompt("Please enter a number:")); // Example output: 42 alert(n1 + n2);
The Number() function is quite flexible. Besides strings, it can also take booleans and values like undefined and null and it will even try to clean any strings for unrelated characters like spaces, tabs, newlines etc. If it can't turn the input into a numeric value, it will return NaN (Not a Number). Here are some examples of how it works:
// 0 alert(Number(null)); // 1 alert(Number(true)); // 42 alert(Number(" 042\t\n ")); // NaN alert(Number("forty-two"));
Convert to string
There can be situations where you want to ensure that you are working with strings as well. This is usually not a problem, because most types can be easily converted into strings using the String() function.
The result of the String() function is quite easy to guess, because it will simply be a string representation of whatever you feed into it, including values like null, undefined etc. Here are some examples:
// 42 alert(String(42)); // true alert(String(true)); // null alert(String(null)); let n1 = String(40); let n2 = String(2); // 402 alert(n1 + n2);
Pay special attention to the last one, where you can clearly see that we have converted our numbers into strings in the way that they are concatenated ("402") instead of added (42).