0

I have this code bellow :

var obj2 = {
  [Symbol.toPrimitive](hint) {
    if (hint == 'number') {
      return 10;
    }
    if (hint == 'string') {
      return 'hello';
    }
    return true;
  }
};

When i call console.log(${obj2}); then function ( Symbol.toPrimitive ) get called with hint = string

I want to know what are the other cases where javascript decide to call symbol.toPrimitive with the argument 'string'

3
  • 1
    whenever obj2 is "coerced" to be a string .. "" + obj2 for example Commented Aug 19, 2021 at 12:07
  • 1
    @Bravo can you give more details please , in case of( ""+obj2) [Symbol.toPrimitive](hint) get called with hint = default Commented Aug 19, 2021 at 12:11
  • I misunderstood the question :p Commented Aug 19, 2021 at 12:36

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

"Naturally, code outside the definition of the spec (like console.log) can call the method explicitly as well." Yes, all Web APIs that take a DOMString as input will call ToString() on the input. So, while console.log shouldn't call it, alert(msg) will.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.