Open In App

JavaScript Symbol for() Method

Improve
Improve
Like Article
Like
Save
Share
Report

The Symbol.for() is an inbuilt method in JavaScript that is used to search for the given symbol in 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 that 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 is 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.

Example 1: In this example, we will use Symbol for() Method.

javascript




// 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);


Output

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

Example 2: In this example, we will use Symbol for() Method.

javascript




// 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);


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



Last Updated : 07 Aug, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads