The JavaScript Symbol.for() method is used to find out the existing symbol in a runtime-wide symbol registry with the provided key. It will create a new symbol if it is not exist fir the specified key.
Syntax:
Symbol.for(key);
Parameters:
key: It represents the specific key for which symbol have to fine.
Returns:
Symbol corresponding to specific key.
Example 1:
<!DOCTYPE html> <html> <body> <script> var alpha = Symbol.for("!"); var beta = Symbol.for("!"); document.write(alpha == beta); </script> </body> </html> |
Output:
true |
Example 2:
<!DOCTYPE html> <html> <body> <script> document.write(Symbol.for('w3spoint') === Symbol.for('w3spoint')); document.write("</br>"); document.write(Symbol('w3spoint') === Symbol('w3spoint')); document.write("</br>"); const symbol = Symbol.for('Jai'); document.write(symbol.toString()); </script> </body> </html> |
Output:
true false Symbol(Jai) |