• JavaScript Video Tutorials

JavaScript - Symbol.valueOf() Method



JavaScript Symbol.valueOf() method can be used to get the primitive value of a Symbol object. Symbols are an immutable, distinct data type that serve as a unique identifier. In order to prevent name conflicts, they are used as keys in object properties.

It invokes the valueOf() method automatically when it encounters a Symbol object and the operation expects a primitive value. This method can be used in situations where primitives are expected, like arithmetic operations or comparisons, because it returns the primitive value associated with the Symbol object.

Syntax

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

valueOf()

Parameters

This property doesn't accepts any kind of parameters.

Return value

This property returns the primitive value of the specified symbol object.

Examples

Example 1

Let's look at the following example, where we are going to compare the two symbols and going to check the output.

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

If we execute the above program, it will display false on the webpage because symbols are unique, even though they look similar.

Example 2

Consider the another example, where we are going to use the Symbol.valueof() method with map.

<html>
   <style>
      body {
         font-family: verdana;
         color: #DE3163;
      }
   </style>
   <body>
      <script>
         const x = Symbol('TP');
         const map = new Map();
         map.set(x, 'WELCOME');
         document.write(map.get(x).valueOf());
      </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 Symbol.valueof() and assign a unique value within the class. It returns its own value even the new instance is created.

<html>
   <style>
      body {
         font-family: verdana;
         color: #DE3163;
      }
   </style>
   <body>
      <script>
         class x {
            constructor() {
               this[Symbol.valueOf()] = 'TutorialsPoint';
            }
         }
         const a = new x();
         document.write(a[Symbol.valueOf()]);
      </script>
   </body>
</html>

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

Advertisements