It's used any time the code uses an operation that "coerces" (implicitly converts) the object to a string, specifically, rather than leaving the decision of what kind of primitive it should be to the object (hint = "default").
There aren't all that many since, again, "default" is more commonly used. The obvious one is explicit conversion to string: String(obj). Other than that, they're mostly around turning a value into a property name. For example if you use an object like this:
someOtherObject[obj] = value;
...obj is converted to string in order to be used as a property name.
const obj = {
[Symbol.toPrimitive](hint) {
console.log(`hint = ${hint}`);
if (hint == 'number') {
return 10;
}
if (hint == 'string') {
return 'hello';
}
return true;
}
};
const otherObject = {};
otherObject[obj] = "some value";
console.log(`otherObject.hello = ${otherObject.hello}`);
For a definitive list of when this happens implicitly, see the specification looking for places where the abstract ToPrimitive operation is used with the argument string and the places where the abstract ToString operation is used. Naturally, code outside the definition of the spec (like console.log) can call the method explicitly as well.
When i call console.log(${obj2}); then function ( Symbol.toPrimitive ) get called with hint = string
Not with all consoles. Some consoles just output their own representation of the object, without converting to string.
"" + obj2for example