JavaScript WTF #1

In ECMA Script 6 toString() function can throw an exception. This makes generating debug output a treacherous minefield. In all other languages I know toString() on built-in objects is safe, and custom toString() implementations that throw an exception are not welcome.

Consider the following code:

function *generator() { yield 42; }
var it = generator();
console.log(it.constructor); // Prints "GeneratorFunction {}"
console.log(it.constructor.toString()); // TypeError: Function.prototype.toString is not generic

So, it actually is possible to print the object to the debug output, but only by itself, no manipulation is allowed. The error message is also quite cryptic: what do they exactly mean by ‘not generic’ and why should I care?

This may seem like a minor annoyance, but I believe it is so brutally violates the rule of least astonishment, that it proudly occupies #1 place among other JavaScript WTFs. In sane languages toString() should not normally fail, at least not for built-in classes. It may, of course, fail with something like OutOfMemoryException, but that’s not what most people would call “normally”. If toString() can throw, I am forced to write a try/catch around every toString() when dealing with unknown objects, and this is, frankly, less than ideal.

2 Comments


  1. Test comment, please ignore

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *