Sub topic 11
Converting to Strings
This chapter assumes you know the seven primitive types, how objects differ from primitives, and the Number edge cases (NaN, -0, Infinity) covered earlier. It explains the ToString abstract operation. ToString is the rule set JavaScript uses whenever it needs a string from a value, whether you call String() yourself or the engine converts the value implicitly.
The ToString Rules for Primitives
Each primitive type has a fixed conversion. You never need to guess.
| Input type | Rule | Example | Result |
|---|---|---|---|
| undefined | The literal word | `String(undefined)` | `"undefined"` |
| null | The literal word | `String(null)` | `"null"` |
| boolean | The literal word | `String(true)` | `"true"` |
| number | Shortest round-tripping decimal | `String(0.5)` | `"0.5"` |
| bigint | Digits, no `n` suffix | `String(10n)` | `"10"` |
| string | Unchanged | `String("hi")` | `"hi"` |
| symbol | TypeError (implicit), description text (via `String()`) | `String(Symbol("id"))` | `"Symbol(id)"` |
| object | ToPrimitive with hint "string", then ToString | `String({})` | `"[object Object]"` |
The diagram shows how ToString picks a path.
Numbers: Where the Surprises Are
Number-to-string conversion follows the algorithm Number::toString. It produces the shortest decimal that converts back to the exact same double. That rule explains several results people don't expect:
console.log(String(0.1 + 0.2)); // "0.30000000000000004"
console.log(String(-0)); // "0": the sign of zero is dropped
console.log(String(NaN)); // "NaN"
console.log(String(-Infinity)); // "-Infinity"
console.log(String(1e21)); // "1e+21": exponent form from 1e21 upward
console.log(String(1e20)); // "100000000000000000000"
console.log(String(0.000001)); // "0.000001"
console.log(String(0.0000001)); // "1e-7": exponent form below 1e-6
console.log(String(2 ** 53 + 1)); // "9007199254740992": precision already lostToString does not round for display. Losing the minus sign on -0 also means String(-0) === String(0), so a string round trip cannot distinguish the two zeros. If you need to tell them apart, use Object.is before converting.
For controlled formatting, use the Number methods instead of ToString:
console.log((255).toString(16)); // "ff": radix conversion
console.log((3.14159).toFixed(2)); // "3.14"
console.log((1.005).toFixed(2)); // "1.00": 1.005 is stored as 1.00499...
console.log((1234.5).toPrecision(2)); // "1.2e+3"
console.log((1234567.891).toLocaleString("en-US")); // "1,234,567.891"BigInt and Symbol
A BigInt converts to its digits without the n suffix, so String(10n) is "10" and ` ${10n} is "10"`. The suffix belongs to literal syntax and is not part of the value.
Symbols are the only primitive that refuses implicit conversion. The language designers made this choice so that a symbol used as a property key never quietly turns into a string by accident.
const id = Symbol("id");
console.log(String(id)); // "Symbol(id)": explicit conversion is allowed
console.log(id.toString()); // "Symbol(id)"
console.log(id.description); // "id": just the description
try {
console.log(`${id}`);
} catch (e) {
console.log(e instanceof TypeError); // true
}
try {
console.log("key: " + id);
} catch (e) {
console.log(e.message); // "Cannot convert a Symbol value to a string"
}String() has a special case for symbols. The template literal and + go straight to ToString, and ToString throws.
Objects: ToPrimitive First
For an object, ToString first calls ToPrimitive with the hint "string". For ordinary objects, that tries toString() before valueOf(). A later chapter covers the full ToPrimitive algorithm. Here you only need the default toString results for the common built-ins:
console.log(String({})); // "[object Object]"
console.log(String([1, 2, 3])); // "1,2,3"
console.log(String([])); // ""
console.log(String([1, [2, [3]]])); // "1,2,3": nested arrays flatten
console.log(String([null, undefined, 1])); // ",,1"
console.log(String(function add(a, b) { return a + b; }));
// "function add(a, b) { return a + b; }": the source text
console.log(String(/ab+c/g)); // "/ab+c/g"
console.log(String(new Error("boom"))); // "Error: boom"Array.prototype.toString calls join(","). join turns null and undefined elements into empty strings, so [null] prints as "" even though String(null) is "null". Every other element goes through ToString. As a result, an array containing a symbol throws:
try {
String([Symbol("x")]);
} catch (e) {
console.log(e instanceof TypeError); // true
}An object with no prototype has no toString or valueOf, so ToPrimitive fails:
const bare = Object.create(null);
try {
String(bare);
} catch (e) {
console.log(e.message); // "Cannot convert object to primitive value"
}The Ways to Ask for a String
Several syntaxes produce strings, and they behave differently on edge cases.
| Expression | `null` | `undefined` | Symbol | Object hint |
|---|---|---|---|---|
| `String(x)` | `"null"` | `"undefined"` | `"Symbol(desc)"` | string |
| `` `${x}` `` | `"null"` | `"undefined"` | TypeError | string |
| `x + ""` | `"null"` | `"undefined"` | TypeError | default |
| `x.toString()` | TypeError | TypeError | `"Symbol(desc)"` | calls method directly |
| `JSON.stringify(x)` | `"null"` | `undefined` (not a string) | `undefined` | serializes |
Two differences matter most in practice:
x.toString()throws whenxisnullorundefined, because those values have no properties.String(x)never throws for them.x + ""uses the default hint, while a template literal uses the string hint. An object whosevalueOfandtoStringdisagree can produce different strings from the two forms:
const price = {
valueOf() { return 9.99; },
toString() { return "$9.99"; }
};
console.log(`${price}`); // "$9.99": string hint, toString first
console.log(price + ""); // "9.99": default hint, valueOf first
console.log(String(price)); // "$9.99"JSON.stringify is a serializer, not a ToString. It quotes strings (JSON.stringify("hi") is '"hi"'), drops undefined and function properties from objects, turns NaN and Infinity into null, and throws a TypeError on BigInt.
console.log(JSON.stringify({ a: undefined, b: NaN, c: "x" })); // '{"b":null,"c":"x"}'
console.log(JSON.stringify(undefined)); // undefinedImplicit ToString in the Language
The engine calls ToString without being asked in several places:
- Template literal substitutions and
+when either operand is a string after ToPrimitive (a later chapter covers this). - Property keys:
obj[1]andobj["1"]refer to the same property, andobj[{}]uses the key"[object Object]". - String methods called with non-string arguments, such as
"abc".includes(null)(which searches for"null") and"a-b".split(undefined). Array.prototype.join,alert, and DOM properties likeelement.textContent = 42.
const cache = {};
cache[{ id: 1 }] = "first";
cache[{ id: 2 }] = "second";
console.log(Object.keys(cache)); // ["[object Object]"]: both keys collidedThis collision happens often when developers use plain objects as maps. Use a Map when your keys are objects.
Exercise
Predict each result: String([null]), String([0, -0]), ${[1, [2, 3]]}, (undefined + "").length, and JSON.stringify([undefined]).
Show answer
String([null]) is "" because join turns null into an empty string. String([0, -0]) is "0,0" because -0 converts to "0". The template literal gives "1,2,3" because nested arrays flatten through join. (undefined + "").length is 9, the length of "undefined". JSON.stringify([undefined]) is "[null]" because JSON writes null for undefined array elements, even though it drops undefined object properties.
Exercise
A logging helper uses "value: " + v. It crashes on some inputs. Which inputs, and what one-word change fixes it?
Show answer
It throws a TypeError for symbols, and for objects whose ToPrimitive fails, such as Object.create(null). Writing "value: " + String(v) fixes the symbol case, because String() special-cases symbols. Prototype-less objects still throw. To handle every value, wrap the conversion in try/catch or fall back to Object.prototype.toString.call(v).