Sub topic 10
Converting Values to Strings
This chapter assumes you can create string literals and template literals, and that you know the basics of objects and arrays. JavaScript converts values to strings constantly, sometimes because you ask it to and sometimes on its own. Most of the time the result is what you expect. The exceptions are null, undefined, symbols, and objects, and those are the cases that cause bugs.
The Three Common Ways to Convert
The main options are String(value), a template literal, and concatenation with +. All three give the same result for numbers, booleans, and strings.
console.log(String(42), `${true}`, 3.5 + ""); // 42 true 3.5
console.log(String(null), String(undefined)); // null undefined
console.log(String(-0)); // 0
console.log(`${[1, [2, 3]]}`); // 1,2,3
console.log(String([null, undefined, 1])); // ,,1
console.log(String({ a: 1 })); // [object Object]Arrays convert by calling join(","). Nested arrays therefore flatten, and null or undefined elements become empty strings. Plain objects become "[object Object]", which is almost never what you want to show a user.
Where the Methods Differ
Calling .toString() directly fails on null and undefined, because those values have no methods. Symbols cause a different failure. String(sym) works, but implicit conversion throws an error.
const sym = Symbol("id");
console.log(String(sym)); // Symbol(id)
try { `${sym}`; } catch (e) { console.log(e.name); } // TypeError
try { sym + ""; } catch (e) { console.log(e.name); } // TypeError
let missing = null;
try { missing.toString(); } catch (e) { console.log(e.name); } // TypeError| Value | `String(v)` | `` `${v}` `` | `v + ""` | `v.toString()` |
|---|---|---|---|---|
| `null` | `"null"` | `"null"` | `"null"` | TypeError |
| `undefined` | `"undefined"` | `"undefined"` | `"undefined"` | TypeError |
| `Symbol("id")` | `"Symbol(id)"` | TypeError | TypeError | `"Symbol(id)"` |
| `[1, 2]` | `"1,2"` | `"1,2"` | `"1,2"` | `"1,2"` |
How Objects Are Converted
For an object, JavaScript first turns it into a primitive. String() and template literals ask for a string, so they try toString() before valueOf(). The + operator gives no hint, so for most objects it tries valueOf() first.
const price = {
valueOf() { return 42; },
toString() { return "$42.00"; },
};
console.log(String(price)); // $42.00
console.log(`${price}`); // $42.00
console.log(price + ""); // 42Date objects are the exception. With + they use the string hint, so new Date() + "" gives a readable date string, not a timestamp.
Formatting While Converting
Some conversions need a specific format, and these methods handle that:
console.log((255).toString(16)); // ff
console.log((0.1 + 0.2).toFixed(2)); // 0.30
console.log(JSON.stringify({ a: 1 })); // {"a":1}
console.log(JSON.stringify("hi")); // "hi" (quotes included)JSON.stringify is the right tool when you need to see what an object contains. Be aware that it adds quotes around strings.
Exercise
What do String([1, null, [2, undefined]]) and ` ${{ toString() { return "T"; }, valueOf() { return 7; } }} ` produce, and why?
Show answer
The first produces "1,,2,". Arrays convert with join(","), nested arrays flatten, and null and undefined elements become empty strings. The second produces "T", because template literals use the string hint and call toString before valueOf.
Exercise
A logging helper uses "Value: " + v. Which input from the table above makes it throw, and what single change fixes it?
Show answer
A symbol throws a TypeError. Writing "Value: " + String(v) fixes it, because String() converts symbols explicitly.