Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symbols: How does implicit string conversion work in JavaScript?

Reading the documentation on Symbols 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 Symbols 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 Symbols have a valid toString() method. So why isn't it called?

like image 555
Patrick Roberts Avatar asked Jan 19 '16 15:01

Patrick Roberts


People also ask

What is implicit conversion in JavaScript?

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.

What is implicit type conversion in JavaScript give an example?

JavaScript Implicit Conversion In certain situations, JavaScript automatically converts one data type to another (to the right type). This is known as implicit conversion.

What are symbols in JS?

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.

What is explicit and implicit in JS?

"Implicitly" means that the JS engine does it. "Explicitly" means that you must do it.


1 Answers

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.

like image 187
Mike Cluck Avatar answered Sep 28 '22 10:09

Mike Cluck