• JavaScript Video Tutorials

JavaScript - Symbol.toString() method



The Symbol.toString() method is a built-in function that allows you to obtain a string representation of a Symbol object. In JavaScript, symbols are a basic data type that are used to generate unique IDs. Symbols are useful for specifying object properties that should be separate from one another because they are unique and immutable, unlike strings or numbers.

It returns a string that represents the symbol when called on an instance of a symbol. When a symbol is contextually forced to a string, such as using template literals or string concatenation, this method is automatically invoked.

Syntax

Following is the syntax of JavaScript Symbol.tostring() method −

Symbol().toString()

Parameters

This method doesn't accepts any parameter.

Return value

This method returns the converted string of the symbol object specified.

Examples

Example 1

Let's look at the following example, where we are going to see the basic usage of the symbol.tostring() method.

<html>
   <style>
      p {
         font-family: verdana;
         color: #DE3163;
      }
   </style>
   <body>
      <p id="demo"></p>
      <script>
         const x = Symbol('TP');
         document.getElementById('demo').innerHTML = x.toString();
      </script>
   </body>
</html>

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

Example 2

Consider the following example, where we are going to use the implicit coercion(automatic conversion to one datatype to another).

<html>
   <style>
      body {
         font-family: verdana;
         color: #DE3163;
      }
   </style>
   <body>
      <script>
         const x = Symbol('Welcome');
         const y = String(x);
         document.write(y);
      </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 create a symbol with an empty description.

<html>
   <style>
      body {
         font-family: verdana;
         color: #DE3163;
      }
   </style>
   <body>
      <script>
         const x = Symbol('');
         document.write(x.toString());
      </script>
   </body>
</html>

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

Example 4

Following is the example, where we are going to use a symbol as a property key.

<html>
   <style>
      body {
         font-family: verdana;
         color: #DE3163;
      }
   </style>
   <body>
      <script>
         const x = Symbol('tp');
         const obj = {};
         obj[x] = 'TutorialsPoint';
         document.write(obj[x]);
      </script>
   </body>
</html>

On executing the above script, the output window will pop up, displaying the text on the webpage.

Advertisements