JavaScript Symbol for() Method
The Symbol.for() is an inbuilt method 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 method accepts a parameter “key” which is the key to the symbol and used for the description of the symbol.
Return value: This method 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 method:
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 method considers that key as the result of the operation.
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/for
Please Login to comment...