Sub topic 10
Converting Values to Strings
This chapter assumes you can write JavaScript functions and objects, use template literals (covered in an earlier chapter), and run code in Node.js or a browser console. JavaScript converts values to strings in many places, often without you asking: in template literals, when you add a value to a string with +, when you print values, and when you use them as object keys. Most of these conversions follow one internal rule, but each way of triggering a conversion has its own edge cases. This chapter covers those edge cases and the errors they cause.
The Four Common Ways to Convert
You can turn a value into a string explicitly or let JavaScript do it implicitly.
| Technique | Example | Works on `null`/`undefined` | Works on Symbol |
|---|---|---|---|
| `String(value)` | `String(42)` | Yes | Yes |
| `value.toString()` | `(42).toString()` | No, throws TypeError | Yes |
| Template literal | `` `${value}` `` | Yes | No, throws TypeError |
| Concatenation | `"" + value` | Yes | No, throws TypeError |
String(value) is the safest general choice because it accepts every type. Calling .toString() fails on null and undefined because they have no properties. Template literals and + throw on symbols on purpose, so that a symbol is never silently turned into text.
const values = [42, true, null, undefined, 10n, Symbol("id")];
for (const v of values) {
console.log(String(v));
}
// 42, true, null, undefined, 10, Symbol(id)
try {
null.toString();
} catch (e) {
console.log(e instanceof TypeError); // true
}
try {
console.log(`${Symbol("id")}`);
} catch (e) {
console.log(e.message); // Cannot convert a Symbol value to a string
}
console.log(Symbol("id").description); // idHow Primitives Convert
Primitive values have fixed string forms. The results for numbers contain most of the surprises.
console.log(String(-0)); // 0
console.log(String(NaN)); // NaN
console.log(String(Infinity)); // Infinity
console.log(String(1e21)); // 1e+21
console.log(String(0.000001)); // 0.000001
console.log(String(0.0000001)); // 1e-7
console.log(String(0.1 + 0.2)); // 0.30000000000000004
console.log(String(123n)); // 123 (no "n" suffix)Note these rules:
-0becomes"0", so the sign is lost. UseObject.is(x, -0)if the sign matters.- Numbers of at least
1e21, and numbers smaller than1e-6, switch to exponential notation. - JavaScript prints the shortest decimal string that round-trips to the same number. Because of that, floating-point error shows up in the output.
- BigInt values convert without their
nsuffix.
Controlling Number Formatting
When the output is meant for people to read, choose a formatting method instead of relying on the default conversion.
const n = 255;
console.log(n.toString(16)); // ff
console.log(n.toString(2)); // 11111111
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(6)); // 1234.50
const fmt = new Intl.NumberFormat("en-US", { style: "currency", currency: "USD" });
console.log(fmt.format(1234.5)); // $1,234.50toString(radix) accepts radixes from 2 to 36. toFixed and toPrecision return strings, so (3.14159).toFixed(2) + 1 gives "3.141", not 4.14. Intl.NumberFormat handles grouping separators, currencies, and locales, which a hand-written formatter usually gets wrong.
How Objects Convert: ToPrimitive
An object cannot become a string directly. JavaScript first reduces it to a primitive with an internal operation called ToPrimitive, then converts that primitive. ToPrimitive receives a hint that says what kind of value is wanted: "string", "number", or "default".
The hint depends on how the conversion was triggered:
| Trigger | Hint | Method order without `Symbol.toPrimitive` |
|---|---|---|
| `String(obj)`, `` `${obj}` ``, property key | `"string"` | `toString`, then `valueOf` |
| `obj + ""`, `obj == "x"` | `"default"` | `valueOf`, then `toString` |
| `+obj`, `obj * 1` | `"number"` | `valueOf`, then `toString` |
This difference matters when an object defines both methods:
const price = {
valueOf() { return 42; },
toString() { return "forty-two"; },
};
console.log(String(price)); // forty-two
console.log(`${price}`); // forty-two
console.log(price + ""); // 42 (default hint prefers valueOf)Date is the main built-in exception. It treats the "default" hint as "string", so new Date() + "" gives a readable date instead of a timestamp.
Defining Symbol.toPrimitive
To control conversion fully, define Symbol.toPrimitive. JavaScript passes it the hint, and it must return a primitive.
const temperature = {
celsius: 21.5,
[Symbol.toPrimitive](hint) {
if (hint === "number") return this.celsius;
return `${this.celsius}°C`;
},
};
console.log(`${temperature}`); // 21.5°C
console.log(temperature + ""); // 21.5°C
console.log(+temperature); // 21.5
console.log(temperature * 2); // 43Default Results for Common Objects
Built-in objects inherit different toString methods, and some of them give results you might not expect.
console.log(String({ a: 1 })); // [object Object]
console.log(String([1, [2, 3]])); // 1,2,3
console.log(String([null, undefined, 1])); // ,,1
console.log(String([])); // "" (empty string)
console.log(String(new Error("boom"))); // Error: boom
console.log(String(function add(a, b) { return a + b; }));
// function add(a, b) { return a + b; }
try {
String(Object.create(null));
} catch (e) {
console.log(e.message); // Cannot convert object to primitive value
}Arrays convert through join(","). That join flattens nested arrays and turns null and undefined into empty strings. Plain objects all become "[object Object]", which is why using an object as a key in another object gives every object the same key. Objects created with Object.create(null) have neither toString nor valueOf, so even String() throws on them.
JSON.stringify Is a Different Operation
JSON.stringify serializes a value as JSON text. It does not perform the string conversion described above, and its rules differ.
console.log(JSON.stringify("hi")); // "hi" (with quotes)
console.log(JSON.stringify({ a: 1, b: [2] })); // {"a":1,"b":[2]}
console.log(JSON.stringify({ a: undefined, f() {} })); // {}
console.log(JSON.stringify([undefined, NaN])); // [null,null]
console.log(JSON.stringify(undefined)); // undefined (not a string)
console.log(JSON.stringify(new Date(0))); // "1970-01-01T00:00:00.000Z"
try {
JSON.stringify(10n);
} catch (e) {
console.log(e instanceof TypeError); // true
}
const cyclic = {};
cyclic.self = cyclic;
try {
JSON.stringify(cyclic);
} catch (e) {
console.log(e instanceof TypeError); // true
}The behavior to remember:
- Object properties whose values are
undefined, functions, or symbols are dropped. In arrays, those values becomenull. NaNandInfinitybecomenull.- BigInt values and circular references throw a TypeError.
JSON.stringify(undefined)returnsundefined, not a string. Code that assumes the result is a string can then fail later.- Objects with a
toJSONmethod, such asDate, are serialized through that method.
Use JSON.stringify(value, null, 2) for indented output when you are debugging object contents. Use String() when you want the value's own text form.
Choosing a Conversion
| Goal | Use |
|---|---|
| Convert any value without throwing on `null`/`undefined` | `String(value)` |
| Build a message from known values | Template literal |
| Show a number to users | `toFixed`, `Intl.NumberFormat` |
| Encode a number in another base | `num.toString(radix)` |
| Inspect an object's contents | `JSON.stringify(value, null, 2)` |
| Customize how your class prints | `toString` or `Symbol.toPrimitive` |
The most common bugs come from these situations: calling .toString() on a value that might be null, putting an object into a template literal and getting "[object Object]", forgetting that toFixed returns a string, and expecting JSON.stringify to keep undefined fields.
Exercise
What does each line print, or does it throw? (a) String([1, null, [2, undefined]]) (b) ` ${Symbol("k")} (c) (0.5).toFixed(0) + 1 (d) JSON.stringify({ x: undefined, y: NaN })`
Show answer
(a) "1,,2," because arrays join with commas, nested arrays flatten, and null and undefined become empty strings. (b) It throws a TypeError, because template literals refuse to convert symbols. Use String(sym) or sym.description instead. (c) "01", because toFixed returns the string "0" (0.5 is rounded to 0 here) and + then concatenates. (d) {"y":null}, because the undefined property is dropped and NaN becomes null.
Exercise
An object has valueOf() { return 7; } and toString() { return "seven"; }. What do String(obj), obj + "", and ` ${obj} ` return, and why?
Show answer
String(obj) and the template literal both return "seven", because they use the "string" hint, which tries toString first. obj + "" returns "7", because the + operator uses the "default" hint, which tries valueOf first. The result 7 is then converted to "7".
Exercise
Write a function safeLabel(value) that returns the string form of any value. It must not throw for null, undefined, symbols, or objects created with Object.create(null).
Show answer
function safeLabel(value) { try { return String(value); } catch { return Object.prototype.toString.call(value); } } String already handles null, undefined, and symbols. The catch branch handles prototype-less objects and returns "[object Object]" for them.