1

I am reading the MDN and ES6 specs definition of Symbol.toStringTag but don't quite get what it means. Is it supposed to be thought of as:

  1. If the toString() method of an object or a class is defined, then the @@toStringTag is irrelevant. (Unless if the self-defined toString() uses @@toStringTag, but in what way?)
  2. Otherwise, Object's toString() will use the function referred to by [Symbol.toStringTag] to obtain an object name to display as [Object XYZ]

?

nonopolarity
  • 146,324
  • 131
  • 460
  • 740
  • 2
    It's related to the ancient way of `Object.prototype.toString.call(new Date) === "[object Date]"`, and accordingly `Object.prototype.toString.call({ [Symbol.toStringTag]: "myNiceName" }) === "[object myNiceName]"` – ASDFGerte Jan 07 '20 at 20:55
  • 1
    Be aware that `@@toStringTag` is not a function, but a string. In contrast to `toString`... – trincot Jan 07 '20 at 20:58
  • 3
    There were (are?) some legacy uses for this, e.g. [how to check if an object is an array](https://stackoverflow.com/questions/4775722/how-to-check-if-an-object-is-an-array), before `Array.isArray`, or other weird runtime type checks. That's because `Object.prototype.toString` [checks internal properties](https://tc39.es/ecma262/#sec-object.prototype.tostring), and was (is?) the only way to check certain things. – ASDFGerte Jan 07 '20 at 21:05
  • @trincot because I saw `class ValidatorClass { get [Symbol.toStringTag]() { return 'Validator'; } }` it looked like there was a `return` involved but it is not a function? – nonopolarity Jan 07 '20 at 21:22
  • 3
    Ah, you are right, it can be a getter. It is accessed as a string property, not called as a function -- although a getter *is* of course called; it is a syntax difference. – trincot Jan 07 '20 at 21:26
  • @nopole for some weird reason, documentation around `@@toStringTag` usually shows using it as a getter. Not sure why since it seems like just extra overhead for trying to understand the concept. Basically, getters are accessed like properties. If you have `obj = {get foo() { return "bar" }}` then `obj.foo == "bar"` and `obj.foo()` is a TypeError because you're doing `"bar"()`. I can only guess they are using a getter since you can't reassign it as a normal property (without a setter). – VLAZ Jan 07 '20 at 21:46
  • @VLAZ I guess the weird reason is that most documentation at the same time tries to show off an ES6 class, where plain-value prototype properties cannot be declared. – Bergi Jan 07 '20 at 23:19

0 Answers0