Reading the documentation on Symbol
s in JavaScript, and also testing in a few environments (Chrome, Firefox, Node.js), I've realized that my understanding of implicit string conversion is flawed.
I was always under the impression that the object's toString()
method was called when attempting to convert to a string, and if that function didn't return a primitive, then it called the object's toPrimitive()
method, then if that didn't work it would type-error. However, this explanation fails to cover the TypeError
that Symbol
s throw:
var sym = Symbol("test");
try {
console.log(sym + "ing");
} catch (error) {
console.error(error);
}
TypeError: Cannot convert a Symbol value to a string
But it's apparent that Symbol
s have a valid toString()
method. So why isn't it called?
You're right that an objects
toString
method is called when doing implicit string conversions. However, as the spec states, implicit string conversions on symbols cause aTypeError
.As Dr. Axel Rauschmayer put it: