whatstheoutput_

#18: String(null) vs null.toString()

Topic: coercion · Difficulty: ★★

console.log(String(null));
try {
  null.toString();
} catch (e) {
  console.log(e.constructor.name);
}

Output

null
TypeError

Why

String(null) is a special-cased global function that has its own explicit rule: given null, just return the literal string 'null' — no property access needed. But null.toString() is a method CALL, which first requires JavaScript to look up .toString on null's 'wrapper object' the way it does for primitives like numbers and strings. null (and undefined) have no wrapper object and no properties at all, so trying to read .toString off them throws a TypeError before the call ever happens.

More coercion puzzles

Play today's puzzle →