String() Coerces Anything, toString() Throws

String() converts any value to text, including null, undefined and symbols; .toString() is a method call and throws TypeError on nullish receivers.

JavascriptData Integrity

Code

javascriptsnippet
18 lines
// String() coerces any value to a string; .toString() is a method call that throws on nullish receivers
const values = [42, 3.14, true, null, undefined, Symbol('id'), [1, 2]];

for (const value of values) {
  console.log(String(value));
}

// String() prints nullish values, while a method call on null throws TypeError
try {
  null.toString();
} catch (error) {
  console.log('null.toString() ->', error.constructor.name);
}

// Practical rule: use String() for possibly-null input instead of guard-then-toString
const toLabel = (value) => (value == null ? '(unset)' : String(value));
console.log('label of null:', toLabel(null));
console.log('label of 0:', toLabel(0)); // 0 is a real value, not replaced by '(unset)'

Output

Captured from a sandboxed run of this snippet in the build pipeline.

42
3.14
true
null
undefined
Symbol(id)
1,2
null.toString() -> TypeError
label of null: (unset)
label of 0: 0

What the demo coerces

The values list spans numbers, booleans, null, undefined, a Symbol and an array. String() prints every one of them — 42, 3.14, true, null, undefined, Symbol(id) and 1,2 — because the function form coerces anything to text.

The method call is not so forgiving: null.toString() throws TypeError, caught and printed. The practical rule lands in toLabel: a nullish input becomes the (unset) marker, while 0, a real value, survives as 0 instead of being treated as unset.

Points to remember

  • String(symbol) works; String is the only coercion that reaches symbols.
  • Guard with value == null so 0 and false are not mistaken for missing.

Interactive Tools for This Topic

FAQ

When does .toString() throw?
When the receiver is null or undefined: the call null.toString() raises TypeError, while String(null) simply prints null.