Skip to content
Related Articles

Related Articles

JavaScript | Symbol.for() function
  • Last Updated : 09 May, 2019

The Symbol.for() is an inbuilt function in JavaScript which is used to search for the given symbol into a runtime-wide symbol registry and if found then it returns the same symbol otherwise it creates a new symbol with the same name of the given symbol into the global symbol registry and returns them.

Syntax:

Symbol.for(key);

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

Parameters: This function accepts a parameter “key” which is the key to the symbol and used for the description of the symbol.

Return value: This function returns the given symbol is found in the runtime-wide symbol registry otherwise a new symbol is created with the same name as the given symbol and returned.



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




<script >
    // Some symbols are created
    const symbol1 = Symbol.for('Geeks');
    const symbol2 = Symbol.for(123);
    const symbol3 = Symbol.for("gfg");
    const symbol4 = Symbol.for('789');
  
    // Getting the same symbols if found 
    // in the global symbol registry
    // otherwise a new created and returned
    console.log(symbol1);
    console.log(symbol2);
    console.log(symbol3);
    console.log(symbol4);
</script>

Output:

> Symbol(Geeks)
> Symbol(123)
> Symbol(gfg)
> Symbol(789)

Example-2:




<script>
    // Some symbols are created
    const symbol1 = Symbol.for('a', 'b', 'c');
    const symbol2 = Symbol.for(1, 2, 3);
    const symbol3 = Symbol.for(1 + 2);
    const symbol4 = Symbol.for("Geeks" + "for" + "Geeks");
  
    // Getting the same symbols if found 
    // in the global symbol registry
    // otherwise a new created and returned
    console.log(symbol1);
    console.log(symbol2);
    console.log(symbol3);
    console.log(symbol4); 
</script>

Output:

> Symbol(a)
> Symbol(1)
> Symbol(3)
> Symbol(GeeksforGeeks)

In the above code, the key should not be multiple otherwise it accepts the first element as the key and discard the remaining elements and if some arithmetic operator is used in place of the key then this function considers that key as the result of the operation.

Supported Browsers:

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

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

full-stack-img

My Personal Notes arrow_drop_up
Recommended Articles
Page :