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?
Javascript's implicit coercion simply refers to Javascript attempting to coerce an unexpected value type to the expected type. So you can pass a string where it expects a number, an object where it expects a string etc, and it will try to convert it to the right type. This is a Javascript feature that is best avoided.
JavaScript Implicit Conversion In certain situations, JavaScript automatically converts one data type to another (to the right type). This is known as implicit conversion.
Symbols are new primitive type introduced in ES6. Symbols are completely unique identifiers. Just like their primitive counterparts (Number, String, Boolean), they can be created using the factory function Symbol() which returns a Symbol. Every time you call the factory function, a new and unique symbol is created.
"Implicitly" means that the JS engine does it. "Explicitly" means that you must do it.
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 a TypeError
.
As Dr. Axel Rauschmayer put it:
Given that both strings and symbols can be property keys, you want to protect people from accidentally converting a symbol to a string.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With