0

Why, when using Symbol.toPrimitive, do we have to return a primitive of the same type as the hint? For example, when using valueOf() and toString(), we can return for example a string for the "number" hint, or for example a number for the "string" hint. But in Symbol.toPrimitive this does not work, as if after the return there is another typecast.

let user = {
  name: 'John',
  money: 1000,

  [Symbol.toPrimitive](hint) {
    return hint == 'string' ? 123 : `this.money`;
  },
};

alert(user); // 123
alert(+user); // NaN

Here we get 123 for string hint and NaN for number hint.

If we do it like this:

let user = {
  name: 'John',
  money: 1000,

  toString() {
    return 123;
  },

  valueOf() {
    return '123';
  },
};

alert(user); // 123
alert(+user); // '123'

As a result, we will get 123 for string hint and '123' for number hint.

Xantc
  • 73
  • 5
  • 1
    Why would you want to do that? – Arye Eidelman Jan 25 '22 at 14:48
  • Shouldn't your "this.money" reference be `${this.money}` inside the template string? – Pointy Jan 25 '22 at 14:50
  • 1
    Are you sure you did not mean `${this.money}` rather than `this.money`? ;) – secan Jan 25 '22 at 14:50
  • ``console.log(+`this.money`)`` is `NaN`. I don't see what the question is. If you return a string that cannot be converted to a number, then you get `NaN`. What other behaviour do you expect? – VLAZ Jan 25 '22 at 14:55
  • 3
    @secan if that's the problem, then I don't see why use a template literal over just `this.money` – VLAZ Jan 25 '22 at 14:56
  • 1
    @VLAZ yea I am very confused that template literals have apparently captivated the imagination of so many people – Pointy Jan 25 '22 at 14:58
  • @VLAZ I thought that + before user object is like a helper for defining hints. – Xantc Jan 25 '22 at 15:12
  • 1
    A unary plus will convert its operand to a number. [What does = +_ mean in JavaScript](https://stackoverflow.com/q/15129137) | [Single plus operator in javascript](https://stackoverflow.com/q/14470973) | [What's the significant use of unary plus and minus operators?](https://stackoverflow.com/q/5450076) `+obj` is the same as doing `Number(obj)` - if `obj` converts to a string that cannot be parsed as number, the result is `NaN`. – VLAZ Jan 25 '22 at 15:18

0 Answers0