W3cubDocs

/JavaScript

Symbol.toStringTag

The Symbol.toStringTag well-known symbol is a string valued property that is used in the creation of the default string description of an object. It is accessed internally by the Object.prototype.toString() method.

Property attributes of Symbol.toStringTag
Writable no
Enumerable no
Configurable no

Examples

Default tags

Object.prototype.toString.call('foo');     // "[object String]"
Object.prototype.toString.call([1, 2]);    // "[object Array]"
Object.prototype.toString.call(3);         // "[object Number]"
Object.prototype.toString.call(true);      // "[object Boolean]"
Object.prototype.toString.call(undefined); // "[object Undefined]"
Object.prototype.toString.call(null);      // "[object Null]"
// ... and more

Built-in toStringTag symbols

Object.prototype.toString.call(new Map());       // "[object Map]"
Object.prototype.toString.call(function* () {}); // "[object GeneratorFunction]"
Object.prototype.toString.call(Promise.resolve()); // "[object Promise]"
// ... and more

Custom classes default to object tag

When creating your own class, JavaScript defaults to the "Object" tag:

class ValidatorClass {}

Object.prototype.toString.call(new ValidatorClass()); // "[object Object]"

Custom tag with toStringTag

Now, with the help of toStringTag, you are able to set your own custom tag:

class ValidatorClass {
  get [Symbol.toStringTag]() {
    return 'Validator';
  }
}

Object.prototype.toString.call(new ValidatorClass()); // "[object Validator]"

toStringTag available on all DOM prototype objects

Due to a WebIDL spec change in mid-2020, browsers are adding a Symbol.toStringTag property to all DOM prototype objects. For example, to acccess the Symbol.toStringTag property on HTMLButtonElement:

let test = document.createElement('button');
test.toString(); // Returns [object HTMLButtonElement]
test[Symbol.toStringTag];  // Returns HTMLButtonElement

Specifications

Browser compatibilityUpdate compatibility data on GitHub

Desktop
Chrome Edge Firefox Internet Explorer Opera Safari
toStringTag 49 15 51 No 36 10
toStringTag available on all DOM prototype objects 50 79 78 No 37 14
Mobile
Android webview Chrome for Android Firefox for Android Opera for Android Safari on iOS Samsung Internet
toStringTag 49 49 51 36 10 5.0
toStringTag available on all DOM prototype objects 50 50 No 37 14 5.0
Server
Node.js
toStringTag 6.0.0
6.0.0
4.0.0
Disabled
Disabled From version 4.0.0: this feature is behind the --harmony runtime flag.
toStringTag available on all DOM prototype objects No

See also

© 2005–2018 Mozilla Developer Network and individual contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
https://wiki.developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/toStringTag