• JavaScript Video Tutorials

JavaScript - Symbol.toStringTag Property



The Symbol.toStringTag property is a built-in symbol value used to customize the default string description of an object. When an object is converted to a string, usually via the Object.prototype.toString() method, it enables developers to supply a custom string representation for the object's type.

JavaScript internally calls Object.prototype.toString() when you call toString() on an object, which returns a string that contains the type of the object. This string representation is [object Object] by default. However, you can alter this representation to provide more details about the kind of object by using the Symbol.toStringTag property.

Syntax

Following is the syntax of JavaScript Symbol.toStringTag property −

Symbol.toStringTag

Parameters

This property doesn't accepts any kind of parameters.

Return value

This property returns a string object.

Examples

Example 1

Let's look at the following example, where we are going to customize toStringTag representation on the user defined objects.

<html>
   <style>
      body {
         font-family: verdana;
         color: #DE3163;
      }
   </style>
   <body>
      <script>
         const x = {
            name: 'Tessa',
            age: 24,
            [Symbol.toStringTag]: 'PersonDetails'
         };
         document.write(Object.prototype.toString.call(x));
      </script>
   </body>
</html>

If we execute the above program, it will displays the text on the webpage.

Example 2

Consider the another scenario, where we are going to customize toStringTag representation for custom classes.

<html>
   <style>
      body {
         font-family: verdana;
         color: #DE3163;
      }
   </style>
   <body>
      <script>
         class Bike {
            constructor(x) {
               this.x = x;
            }
            get[Symbol.toStringTag]() {
               return 'Bike';
            }
         }
         const a = new Bike('R15');
         document.write(Object.prototype.toString.call(a));
      </script>
   </body>
</html>

On executing the above script, it will displays a text on the webpage.

Example 3

In the following example, we are going to use the Symbol.toStringTgat with derived class.

<html>
   <style>
      body {
         font-family: verdana;
         color: #DE3163;
      }
   </style>
   <body>
      <script>
         class x extends Array {
            get[Symbol.toStringTag]() {
               return 'TP';
            }
         }
         const y = new x(11, 22, 33);
         document.write(Object.prototype.toString.call(y));
      </script>
   </body>
</html>

When we execute the script, it will displays a text on the webpage.

Advertisements