Explicit type conversion
Learn explicit type conversion with String(), Number() and Boolean().
Explicit type conversion
In JavaScript you sometimes want to explicitly convert a value to another type. There are three built-in functions for this: String(), Number() and Boolean().
Examples: String(42) gives "42"; Number("42") gives 42; Boolean(0) gives false. These are called explicit conversions because you state your intent clearly in the code.
Number() and Boolean() details
Number() converts a string into a number. If there is no valid number it returns NaN: Number("42") → 42, Number("42px") → NaN.
Boolean() turns a value into true or false. Empty values (0, "", null, undefined, NaN) become false; everything else becomes true. So Boolean("") gives false, while Boolean("hello") gives true.
Exercise Triple conversion function
Define a function called describeConversions. It should take a value parameter. In the body write three lines: console.log(String(value)), console.log(Number(value)) and console.log(Boolean(value)).
Show example solution
function describeConversions(value) {
console.log(String(value));
console.log(Number(value));
console.log(Boolean(value));
}
Exercise Call the function with different values
The describeConversions function below is defined. Now call it with three values: describeConversions("0"), describeConversions(0) and describeConversions(""). Put each call on its own line.
Show example solution
function describeConversions(value) {
console.log(String(value));
console.log(Number(value));
console.log(Boolean(value));
}
describeConversions("0");
describeConversions(0);
describeConversions("");
Test yourself
-
Which explicitly converts the number 42 to a string?
- String(42)
- 42.toString()
- str(42)
- toStr(42)
Show answer
String(42) — Correct. String(42) converts the number 42 into the string "42".
-
Convert the string to a number
let text = "42"; let num = ____(text); console.log(num + 1);Show answer
let text = "42"; let num = Number(text); console.log(num + 1);