Output formatting
Displaying a value through an API or output operation that requires text.
JS Puzzles · Const
String coercion converts a value to text when JavaScript needs its string form. It happens implicitly in suitable operations or explicitly with String(value).
JavaScript converts a value to text when an operation needs a string, such as displaying it. This conversion can happen implicitly, or explicitly with String(value). Common values receive predictable textual forms: booleans become "true" or "false", null becomes "null", and numbers become their textual representation.
String(value)| Name | Type | Description |
|---|---|---|
value | any | The value whose textual representation is required. |
A string representation of the supplied value.
let value = true;
console.log(String(value)); // "true"
console.log(String(null)); // "null"
console.log("" + 1 + 2); // "12"Use String(value) when an explicit string conversion is intended; concatenation can produce different results because + handles strings and numbers differently.
Displaying a value through an API or output operation that requires text.
Making the conversion intent explicit before storing or passing textual data.
Converting booleans or null into predictable text for labels or messages.
String coercion occurs when JavaScript needs the string form of a value, such as while displaying it. It can also be requested explicitly with String(value).
Follow-up: What does String(false) return? It returns the string "false", not the boolean false.
String(true) produces "true", and String(null) produces "null". The result is a string even though the inputs have different types.
Follow-up: How would you verify the result type? Apply typeof to the converted value; it returns "string".
String conversion is distinct from numeric conversion: String(value) creates textual output, whereas arithmetic operators may convert operands to numbers. Use String when the required result is a string.
Follow-up: What happens when a string is passed to Number instead? A numeric string can become a number, while an invalid numeric string becomes NaN.
Number conversionBoolean conversionType conversions