How does toString work?

👨‍💻 Frontend Developer 🟠 May come up 🎚️ Medium
#JavaScript #Type Coercion #String

Brief Answer

  • String(value) — explicit conversion to string per spec (ToString).
  • value.toString() — a method on objects/primitives; missing for null/undefined.
  • Concatenation ('' + value) and template literals (${value}) perform implicit string coercion.

Full Answer

Explicit vs implicit

  • Explicit: String(value) — safe for any value including null/undefined.
  • Method: value.toString() — may be absent or overridden.
  • Implicit: '' + value or ${value} — engine runs ToPrimitive then ToString.

Mini examples:

String(123);        // "123"
(123).toString();   // "123"
'' + 123;           // "123"

Primitives

  • Numbers: String(1.2)"1.2", String(NaN)"NaN", String(Infinity)"Infinity".
  • Booleans: String(true)"true", String(false)"false".
  • null/undefined: String(null)"null", String(undefined)"undefined"; they have no toString().

Mini examples:

String(null);       // "null"
String(undefined);  // "undefined"
// null.toString()  // TypeError

Arrays and objects

  • Arrays: [].toString()"", [1,2].toString()"1,2".
  • Plain objects: default "[object Object]" via Object.prototype.toString, unless overridden.

Mini examples:

[1, 2].toString();     // "1,2"
({}).toString();       // "[object Object]"

Override toString:

const user = { name: 'Ada', toString() { return `User:${this.name}`; } };
String(user);          // "User:Ada"

Symbols

  • symbol.toString()"Symbol(desc)".
  • '' + symbol may throw; prefer String(symbol) or symbol.toString().

Mini example:

const s = Symbol('x');
s.toString();          // "Symbol(x)"

Template literals and concatenation

Both coerce values to string:

`${true}`;            // "true"
'' + [1, 2];          // "1,2"

Common pitfalls

  • Calling toString on null/undefined — TypeError.
  • Expecting “nice” default object output — you get "[object Object]"; override toString or use JSON.stringify.

Mini example:

JSON.stringify({ a: 1 }); // "{\"a\":1}"

Recommendations

  • Need reliability: use String(value).
  • Need formatting control: override your object’s toString().
  • For UI/logs avoid "[object Object]": use toString or JSON.stringify.