• JavaScript Video Tutorials

JavaScript - Symbol.keyFor() Method



The Symbol.keyFor() method is used to retrieve the string key associated with a given symbol from the global symbol registry. If a symbol is created using this method, it is registered in a global symbol registry with the specified key. This registry allows the symbols to be shared across different modules or different parts of the program.

The Symbol.keyFor() method returns the key under which the symbol is registered in the global symbol registry. It returns undefined, if the symbol is not found in the registry.

Syntax

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

Symbol.keyFor(symbol); 

Parameters

This method accepts only one parameter. The same is described below −

  • symbol − A symbol whose key is to be retrived.

Return value

This method returns the key corresponding to specific symbol.

Examples

Example 1

Let's look at the following example, where we are going to create a symbol using the Symbol.for() and retrieving the output.

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

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

Example 2

Consider another scenario where we are going to create a symbol that is not added to the global symbol registry and retrieve the output.

<html>
   <style>
      body {
         font-family: verdana;
         color: #DE3163;
      }
   </style>
   <body>
      <script>
         const x = Symbol('TutorialsPoint');
         document.write(Symbol.keyFor(x));
      </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 two symbols with different keys and perform a comparison.

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

When we execute the above script, the output window will pop up, displaying the text 'true', indicating that both symbols are not equal.

Advertisements