Skip to content
Related Articles
Get the best out of our app
GeeksforGeeks App
Open App
geeksforgeeks
Browser
Continue

Related Articles

JavaScript Symbol keyFor() Method

Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article

The Symbol.keyFor() is an inbuilt method 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 method accepts a parameter “sym” which is the symbol for which the key is to be found.

Return value: This method 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 method.
Example-1:




<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() method 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>

Output:

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

Example-2:




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

Output:

"undefined"
"undefined"

Supported Browsers:

  • Google Chrome 40 and above
  • Edge 12 and above
  • Firefox 36 and above
  • Opera 27 and above
  • Safari 9 and above

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


My Personal Notes arrow_drop_up
Last Updated : 18 May, 2023
Like Article
Save Article
Similar Reads
Related Tutorials