JavaScript Symbol() Constructor
The Symbol() constructor is used to create a new symbol. The Symbol() constructor returns a value of the type of symbol with static properties. Every time we call the constructor a unique symbol is created. A Symbol constructor is a primitive data type having no object or no methods which are generally used as an identifier.
Syntax:
Symbol(str)
Arguments: The only argument is an optional string that is used for debugging but not to access the symbol. It means every time we call Symbol() constructor a unique symbol is created.
Return value: The Symbol() constructor returns a value of the type of symbol. And every time a unique symbol is returned.
Example 1: Below is the example of the Symbol() constructor.
Javascript
<script> function func() { // symbol without any parameter const sym1 = Symbol(); // symbol with parameter const sym2 = Symbol(9); // symbol with string const sym3 = Symbol( "GFG" ); console.log(sym2.toString()); // Type of symbol 1 console.log( typeof sym1); // Check symbol is equal to "GFG" or not console.log(sym3== "GFG" ); } func(); </script> |
Output:
Symbol(9) symbol false
Example 2: In this example, the constructor creates a new primitive symbol const sym1 = Symbol();
Javascript
<script> function func() { // symbol without any parameter const sym1 = Symbol(); console.log(sym1); } func(); </script> |
Output:
Symbol()
Example 3: In this example, the constructor creates a new primitive symbol with an argument const sym2 = Symbol(9);
Javascript
<script> function func() { // symbol with a parameter const sym2 = Symbol(9); console.log(sym2.toString()); } func(); </script> |
Output:
Symbol(9)
Example 4: In this example, the constructor creates a new primitive symbol with a string argument const sym3 = Symbol(“GFG”);
Javascript
<script> function func() { // symbol without a string parameter const sym3 = Symbol( "GFG" ); console.log(sym3); } func(); </script> |
Output:
Symbol(GFG)
Example 5: In this example, we compare the return symbol with the string and return true if both are equal, otherwise, it returns false. Since the Symbol() constructor returns only a symbol, its output is false, console.log(sym3 == “GFG”);.
Javascript
<script> function func() { // symbol with string const sym3 = Symbol( "GFG" ); // Check symbol is equal to "GFG" or not console.log(sym3== "GFG" ); } func(); </script> |
Output:
false