JavaScript | Symbol.keyFor() function

The Symbol.keyFor() is an inbuilt function in JavaScript which is used to retrieve the key which has been shared with the given symbols and this key is retrieved from the global symbol registry.

Syntax:

Symbol.keyFor(sym);

Here “Symbol” is the symbol which is to be searched into the runtime-wide symbol registry.



Parameters: This function accepts a parameter “sym” which is the symbol for which the key is to be found.

Return value: This function returns a string representing the key for the given symbol is found in the global registry otherwise it returns undefined.

JavaScript code to show the working of this function.
Example-1:

filter_none

edit
close

play_arrow

link
brightness_4
code

<script>
    // Some symbols are created
    // with proper key
    const sym1 = Symbol.for('Geeks');
    const sym2 = Symbol.for(123);
    const sym3 = Symbol.for("gfg");
    const sym4 = Symbol.for('789');
  
    // Calling the keyFor() function and
    // getting the key for the above symbols
    console.log(Symbol.keyFor(sym1));
    console.log(Symbol.keyFor(sym2));
    console.log(Symbol.keyFor(sym3));
    console.log(Symbol.keyFor(sym4)); 
</script>

chevron_right


Output:

"Geeks"
"123"
"gfg"
"789"

Example-2:

filter_none

edit
close

play_arrow

link
brightness_4
code

<script>
    // Creating some symbols without key
    const sym1 = Symbol.for();
    const sym2 = Symbol.iterator;
  
    // Calling the keyFor() function and
    // getting the key for the above symbols
    console.log(Symbol.keyFor(sym1));
    console.log(Symbol.keyFor(sym2)); 
</script>

chevron_right


Output:

"undefined"
"undefined"

Supported Browsers:

  • Google Chrome
  • Firefox
  • Edge
  • Opera
  • Apple Safari

Reference: https://devdocs.io/javascript/global_objects/symbol/keyfor



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.